Created
June 23, 2022 07:18
-
-
Save eutkin/46b7986bd91326077ae6ade59b9e2f81 to your computer and use it in GitHub Desktop.
This file contains 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.github.eutkin; | |
@SuppressWarnings("UNCHECKED_CAST") | |
public class ArrayList<T> implements List<T> { | |
private Object[] array; | |
private int size; | |
public ArrayList(int initialCapacity) { | |
this.array = new Object[initialCapacity]; | |
this.size = 0; | |
} | |
@Override | |
public T get(int index) { | |
return (T) this.array[index]; | |
} | |
@Override | |
public void add(T element) { | |
this.array[this.size] = element; | |
this.size++; | |
if (this.array.length == this.size) { | |
resize(size * 2); | |
} | |
} | |
@Override | |
public void remove(int index) { | |
this.array[index] = null; | |
// все сложнее | |
} | |
private void resize(int capacity) { | |
Object[] newArray = new Object[capacity]; | |
System.arraycopy(this.array, 0, newArray, 0, this.array.length); | |
this.array = newArray; | |
} | |
@Override | |
public String toString() { | |
StringBuilder sb = new StringBuilder("["); | |
for (int i = 0; i < this.size - 1; i++) { | |
sb.append(this.array[i]); | |
sb.append(','); | |
} | |
sb.append(this.array[this.size - 1]); | |
return sb.append(']').toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment