Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyListImpl<T> implements MyList<T> {
- private T[] elements;
- private int size;
- private int capacity;
- public MyListImpl() {
- this.capacity = 4;
- this.elements = (T[]) new Object[this.capacity];
- this.size = 0;
- }
- public MyListImpl(int capacity) {
- this.capacity = capacity;
- this.elements = (T[]) new Object[this.capacity];
- this.size = 0;
- }
- @Override
- public int size() {
- return size;
- }
- @Override
- public int capacity() {
- return capacity;
- }
- @Override
- public T get(int index) {
- if (index < 0 || index >= size) {
- throw new ArrayIndexOutOfBoundsException("Index out of bounds");
- }
- return elements[index];
- }
- @Override
- public void add(T element) {
- if (size == capacity) {
- resize();
- }
- elements[size++] = element;
- }
- private void resize() {
- capacity *= 2;
- T[] newElements = (T[]) new Object[capacity];
- System.arraycopy(elements, 0, newElements, 0, size);
- elements = newElements;
- }
- @Override
- public boolean contains(T element) {
- for (int i = 0; i < size; i++) {
- if (elements[i].equals(element)) {
- return true;
- }
- }
- return false;
- }
- @Override
- public int indexOf(T element) {
- for (int i = 0; i < size; i++) {
- if (elements[i].equals(element)) {
- return i;
- }
- }
- return -1;
- }
- @Override
- public int lastIndexOf(T element) {
- for (int i = size - 1; i >= 0; i--) {
- if (elements[i].equals(element)) {
- return i;
- }
- }
- return -1;
- }
- @Override
- public boolean remove(T element) {
- int index = indexOf(element);
- if (index != -1) {
- removeAt(index);
- return true;
- }
- return false;
- }
- @Override
- public void removeAt(int index) {
- if (index < 0 || index >= size) {
- throw new ArrayIndexOutOfBoundsException("Index out of bounds");
- }
- for (int i = index + 1; i < size; i++) {
- elements[i - 1] = elements[i];
- }
- size--;
- }
- @Override
- public void clear() {
- size = 0;
- }
- @Override
- public void swap(int from, int to) {
- if (from < 0 || from >= size || to < 0 || to >= size) {
- throw new ArrayIndexOutOfBoundsException("Index out of bounds");
- }
- T temp = elements[from];
- elements[from] = elements[to];
- elements[to] = temp;
- }
- @Override
- public Iterator<T> iterator() {
- return new IteratorImpl<>();
- }
- private class IteratorImpl<T> implements Iterator<T> {
- private int index = 0;
- @Override
- public boolean hasNext() {
- return index < size;
- }
- @Override
- public T next() {
- if (!hasNext()) {
- throw new NoSuchElementException();
- }
- return MyListImpl.this.elements[index++];
- }
- }
- @Override
- public void print() {
- System.out.print("[");
- for (int i = 0; i < size; i++) {
- System.out.print(elements[i]);
- if (i < size - 1) {
- System.out.print(", ");
- }
- }
- System.out.println("]");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement