Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/out/
/.idea/

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отлично, что дополнил!
Для полноты нужно еще *.iml добавить.

209 changes: 209 additions & 0 deletions src/Tkhorzhevskiy/DimbossArrayList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
package Tkhorzhevskiy;

import java.util.*;


public class DimbossArrayList<E> implements List<E> {

private E[] listArr;
private int size;
private static final int DEFAULT_SIZE=10;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Круто, что выделил в константу


public DimbossArrayList() {
listArr = (E[]) new Object[10];
size = 0;
}


public void ensureCapacity(int minCapcity) {
int currentCapacity = listArr.length;
if (minCapcity > currentCapacity) {
E[] oldListArr = listArr;
listArr = (E[]) new Object[minCapcity];
for (int i = 0; i < size; i++)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не забывай, хоть джава и позволяет тело цикла писать без фигурных скобок, лучше все же писать его с ними. Так ты сокращаешь количество возможных ошибок в будущем.
Это же касается и ифов.

listArr[i] = oldListArr[i];
oldListArr = null;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А что вот этой строчкой хотел сделать? Я не очень понял, но, может, смогу подсказать, как сделать лучше, если пойму.

}
}


public void rangeCheck(int index, String msg, int upperBound) {
if (index < 0 || index >= upperBound + 1)
throw new IndexOutOfBoundsException(msg + " индекс" + index + " находится за границей массива");
}


public void add(int index, E element) {
rangeCheck(index, "Arraylist add()", size);
if (listArr.length == size)
ensureCapacity(2 * listArr.length);
for (int j = size - 1; j >= index; j--) {
listArr[j + 1] = listArr[j];
}
listArr[index] = element;
size++;
}

@Override
public int size() {
return size;
}

@Override
public boolean isEmpty() {
return size == 0;
}

@Override
public boolean contains(Object o) {
for (int i = 0; i < size; i++)
if (listArr[i] == o)
return true;
return false;
}

@Override
public Iterator<E> iterator() {
return null;
}

@Override
public Object[] toArray() {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отлично, только можно бы было чутка докрутить с дженериками и получить что-то типа такого:

    @Override
    public E[] toArray() {
        Object[] arr = new Object[size()];
        for (int i = 0; i < size(); i++) {
            arr[i] = get(i);
        }
        return (E[]) arr.clone();
    }

Object[] arr = new Object[size()];
for (int i = 0; i < size(); i++) {
arr[i] = get(i);
}
return arr.clone();
}

@Override
public <E1> E1[] toArray(E1[] a) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем еще один дженерик ввел? У тебя же есть общий для всего класса - E

Object[] arr = new Object[size()];
for (int i = 0; i < size(); i++) {
arr[i] = get(i);
}
return (E1[]) arr.clone();
}

@Override
public boolean add(E t) {
add(size, t);
return true;
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы предложил методы группировать пологичнее. Например, помещать перегруженные add рядом друг с другом. remove тоже рядом.


@Override
public boolean remove(Object o) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Слушай, а почему бы тебе не осуществлять здесь поиск по объекту с определением индекса, а потом вызвать remove по индексу? Переиспользуешь код почти нахаляву.

int i;
for (i = 0; i < size; i++)
if (listArr[i] == o)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему через == сравниваешь, а не через equals?

break;
if (i == size)
return false;
for (int j = i - 1; j < size; j++)
listArr[j] = listArr[j + 1];
size--;
return true;

}

@Override
public boolean containsAll(Collection<?> c) {
return false;
}

@Override
public boolean addAll(Collection<? extends E> c) {
return false;
}

@Override
public boolean addAll(int index, Collection<? extends E> c) {
return false;
}

@Override
public boolean removeAll(Collection<?> c) {
return false;
}

@Override
public boolean retainAll(Collection<?> c) {
return false;
}

@Override
public void clear() {
listArr = (E[]) new Object[DEFAULT_SIZE];
}

@Override
public E get(int index) {
return listArr[index];
}

@Override
public E set(int index, E element) {
rangeCheck(index, " установить индекс ", size - 1);
listArr[index] = element;
return element;
}

@Override
public E remove(int index) {

rangeCheck(index, " удалить индекс ", size - 1);
E r = listArr[index];
for (int i = index; i < size; i++)
listArr[i] = listArr[i + 1];
size--;
return r;
}

@Override
public int indexOf(Object o) {
for (int i = 0; i < size; i++)
if (listArr[i] == o)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему через == сравниваешь, а не через equals?

return i;
return -1;
}

@Override
public int lastIndexOf(Object o) {
return 0;
}

@Override
public ListIterator<E> listIterator() {
return null;
}

@Override
public ListIterator<E> listIterator(int index) {
return null;
}

@Override
public List<E> subList(int fromIndex, int toIndex) {
return null;
}

public static void main(String [] args){

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

main лучше выносить в отдельный класс.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не провел сравнение производительности своей реализации ArrayList со стандартной

DimbossArrayList<Integer> testList=new DimbossArrayList<>();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Все еще проблемы с форматированием.
Не забывай про ctrl + alt + L.

testList.add(2);
testList.add(2);
testList.add(8);
System.out.println(testList.get(0));
System.out.println(testList.size());
System.out.println(testList.isEmpty());
System.out.println(testList.contains(7));
System.out.println(testList.remove(2));
System.out.println(testList.contains(1));
testList.set(1,6);
System.out.println(testList.indexOf(6));
Object[] arr=testList.toArray();
System.out.println(Arrays.toString(arr));
}



}