Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company.oop;
- import java.util.Iterator;
- public class MyListImpl<T> implements MyList<T> {
- public static final int DEFAULT_INITIAL_CAPACITY = 4;
- int capacity;
- int size = 0;
- T[] array;
- public MyListImpl(int initialCapacity) {
- if (initialCapacity < 1) {
- throw new IndexOutOfBoundsException();
- }
- this.capacity = initialCapacity;
- array = (T[]) new Object[capacity];
- }
- public MyListImpl() {
- this(DEFAULT_INITIAL_CAPACITY);
- }
- @Override
- public int size() {
- return this.size;
- }
- @Override
- public int capacity() {
- return this.capacity;
- }
- @Override
- public void add(T element) {
- if (size >= capacity) {
- doubleCapacityOfArray();
- }
- array[size] = element;
- size++;
- }
- private void doubleCapacityOfArray() {
- capacity *= 2;
- T[] tempArray = array.clone();
- array = (T[]) new Object[capacity];
- System.arraycopy(tempArray, 0, array, 0, tempArray.length);
- }
- @Override
- public T get(int index) {
- if (index >= 0 && index < size) {
- return array[index];
- }
- throw new IndexOutOfBoundsException();
- }
- @Override
- public int indexOf(T element) {
- for (int i = 0; i < size; i++) {
- if (array[i].equals(element)) {
- return i;
- }
- }
- return -1;
- }
- @Override
- public int lastIndexOf(T element) {
- for (int i = size - 1; i >= 0; i--) {
- if (array[i].equals(element)) {
- return i;
- }
- }
- return -1;
- }
- @Override
- public boolean contains(T element) {
- for (int i = 0; i < size; i++) {
- if (array[i].equals(element)) {
- return true;
- }
- }
- return false;
- }
- @Override
- public void removeAt(int index) {
- if (index < 0 || index >= size) {
- throw new ArrayIndexOutOfBoundsException();
- }
- // 1 2 3 4 0 0 0 0
- for (int i = index; i < size - 1; i++) {
- array[i] = array[i + 1];
- }
- size--;
- array[size] = null;
- }
- @Override
- public boolean remove(T element) {
- // 1 2 3 4 null null null null
- if (!contains(element)) {
- return false;
- }
- int startIndex = indexOf(element);
- removeAt(startIndex);
- return true;
- }
- @Override
- public void clear() {
- array = (T[]) new Object[capacity];
- }
- @Override
- public void swap(int from, int to) {
- // 1 2 3 4 0 0 0 0
- if (from < 0 || to < 0 || from >= size || to >= size) {
- throw new IndexOutOfBoundsException();
- }
- T tempEl1 = array[from];
- T tempEl2 = array[to];
- array[from] = tempEl2;
- array[to] = tempEl1;
- }
- @Override
- public void print() {
- System.out.print("[");
- for (int i = 0; i < size; i++) {
- if (i == size - 1) {
- System.out.println(array[size - 1] + "]");
- } else {
- System.out.print(array[i] + ", ");
- }
- }
- }
- @Override
- public Iterator<T> iterator() {
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement