Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class ArrayList {
- private static Object[] array = new Object[16];
- private int size = 0;
- public void add(Object e) {
- if (size - array.length >= 0) {
- ensureCapacity(size + 1);
- }
- array[size++] = e;
- }
- public void add(int i, Object e) {
- if ((i >= size) || (i < 0)) {
- throw new IndexOutOfBoundsException();
- }
- if (size - array.length > 0) {
- ensureCapacity(size + 1);
- }
- for (int j = size-1; j >= i; j--) {
- array[j+1] = array[j];
- }
- array[i] = e;
- size++;
- }
- public void clear() {
- for (int i = 0; i < size; i++) {
- array[i] = null;
- }
- size = 0;
- }
- public boolean contains(Object e) {
- if (e == null) {
- for (int i = 0; i < size; i++) {
- if (array[i] == null) {
- return true;
- }
- }
- } else {
- for (int i = 0; i < size; i++) {
- if (e.equals(array[i])) {
- return true;
- }
- }
- }
- return false;
- }
- public void ensureCapacity(int minCapacity) {
- if (minCapacity > array.length) {
- Arrays.copyOf(array, (minCapacity - 1) * 2);
- }
- }
- public Object get(int i) {
- if ((i >= size) || (i < 0)) {
- throw new IndexOutOfBoundsException();
- }
- return array[i];
- }
- public int indexOf(Object e) {
- if (e == null) {
- for (int i = 0; i < size; i++) {
- if (array[i] == null) {
- return i;
- }
- }
- } else {
- for (int i = 0; i < size; i++) {
- if (e.equals(array[i])) {
- return i;
- }
- }
- }
- return -1;
- }
- public boolean isEmpty() {
- return size == 0;
- }
- public Object remove(int i) {
- if ((i >= size) || (i < 0)) {
- throw new IndexOutOfBoundsException();
- }
- Object a = array[i];
- for (int j = i + 1; j < size; j++) {
- array[j - 1] = array[j];
- }
- array[size - 1] = null;
- size--;
- return a;
- }
- public boolean removeObject(Object e) {
- int i = indexOf(e);
- if (i != -1) {
- remove(i);
- // а извлеченный элемент остается в памяти?
- return true;
- }
- return false;
- }
- public Object set(int i, Object e) {
- if ((i >= size) || (i < 0)) {
- throw new IndexOutOfBoundsException();
- }
- Object a = array[i];
- array[i] = e;
- return a;
- }
- public int size() {
- return size;
- }
- public Object[] trimToSize() {
- Object[] newarray = new Object[size];
- int i = 0;
- while (array[i] != null) {
- newarray[i] = array[i];
- i++;
- }
- return newarray;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement