Last active
December 19, 2021 10:21
-
-
Save sunmeat/c3dccc2b0e9fbed740dc to your computer and use it in GitHub Desktop.
array list. the beginning...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.alex.collections; | |
class MyArrayList { | |
private int size = 0; | |
private int capacity = 10; | |
private int[] data; | |
public MyArrayList() { | |
// data = new int[capacity]; // вместо копирования кода - применяется делегирование конструкторов! | |
this(10); | |
System.out.println("MyArrayList default c-tor!"); // эта строчка отладочная, в итоговой версии её быть не должно! | |
} | |
public MyArrayList(int capacity) { | |
if (capacity < 10) { | |
capacity = 10; | |
} | |
this.capacity = capacity; | |
data = new int[capacity]; | |
System.out.println("MyArrayList parametrized c-tor!"); // отладочная строка кода | |
} | |
public void pushBack(int value) { | |
// ensureCapacity(size+1); // проверку, хватит ли места для нового элемента - делайте сами :) | |
data[size++] = value; | |
} | |
public void pushFront(int value) { | |
// ensureCapacity(size+1); | |
for (int i = size; i > 0; i--) { | |
data[i] = data[i - 1]; | |
} | |
data[0] = value; | |
size++; | |
} | |
public void clear() { | |
for (int i = 0; i < size; i++) { | |
data[i] = 0; | |
} | |
size = 0; | |
} | |
public boolean isEmpty() { | |
return size == 0; // красота :) | |
} | |
public void print() { | |
if (isEmpty()) { | |
System.out.println("Collection is empty."); | |
} else { | |
for (int i = 0; i < size; i++) { | |
System.out.print(data[i] + " "); | |
} | |
System.out.println(); | |
} | |
} | |
// другие методы обязательно появятся здесь... | |
} | |
class Program { | |
public static void main(String[] args) { | |
// тесты работы с эррейлистом: | |
MyArrayList ar = new MyArrayList(); | |
ar.pushBack(12); | |
ar.pushBack(18); | |
ar.pushBack(16); | |
ar.print(); | |
ar.pushFront(14); | |
ar.print(); | |
ar.clear(); | |
ar.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment