JavaRush /Java Blog /Random EN /Detailed analysis of the ArrayList class [Part 2]
Vonorim
Level 26

Detailed analysis of the ArrayList class [Part 2]

Published in the Random EN group
Unfortunately, all the information did not fit into one article, so we continue to look at the remaining methods of the ArrayList class. Sort collection:
public void sort(Comparator< ? super E> c)
Sorts the list according to a given rule. A sort rule is an implemented Comparator interface with an overridden compare(). Overriding is necessary if the collection contains objects of its own class. When working with standard classes (Integer, String, and so on), the compare override is usually only needed for non-standard sorting. Let's create a class Student:
class Student{
 String student_name;
 int id;

 Student(int id, String  student_name){
  this.id = id;
  this.student_name = student_name;
 }

 public String toString(){
  return id + " " + student_name;
 }
}
Let's write a simple comparator that will compare student ids:
class StudentIdComparator implements Comparator<student>{

 public int compare(Student e1, Student e2) {
  return e1.id.compareTo(e2.id);
 }
}
Let's create a list for students and a class object that implements Comparator:
ArrayList<Student> myList = new ArrayList<> ();
StudentIdComparator comparator = new StudentIdComparator();
Let's call the method sortfor our list and pass the comparator to it:
myList.sort(comparator);
This will turn the original list [4 David, 2 Tom, 5 Rohit, 1 Paul, 3 Vishal] into [1 Paul, 2 Tom, 3 Vishal, 4 David, 5 Rohit]. For last I left a very interesting, but rarely used method:
public List<E> subList(int fromIndex, int toIndex)
It does not return a new list, as it might seem, but a view of the list (sublist) for which this method was called, so that both lists will share the stored elements. subList is a fully functional list; it also works for writing, making appropriate changes to the parent list. Excellent properties follow from this:
someList.subList(3, 7).clear();
In this example, someListfour elements will be removed from the list, from the third to the seventh (not inclusive). We indicate the range for working with the list and off we go. Inside the method, in essence, there is a call to the SubList class, which has its own implementations of known methods, and as a result of the method's operation, an object of this class is returned. The implementation of the class itself can be viewed in the source code . To consolidate the material, I suggest you write your own implementation of a dynamic array. This will be very useful in the future. As an example, I present my implementation of a dynamic array for numbers only, with comments in the code.
public class IntegerArrayList {

    private int [] elements;  //массив, для хранения чисел
    private int size;  //поле-счетчик, которое указывает на количество элементов в массиве
    private static final int DEFAULT_CAPACITY = 10;  //размер массива по умолчанию

    //конструктор без параметров, который создает массив на 10 элементов, если размер не был указан
    public IntegerArrayList(){  //
        this.elements = new int[DEFAULT_CAPACITY];
    }

    //создает массив указанной емкости
    public IntegerArrayList(int initialCapacity){
        if (initialCapacity >= 0){
            this.elements = new int[initialCapacity];
        }
        else {
            throw new IllegalStateException("Capacity can't be less than 0!");
        }
    }

    //получает элемент по указанному индексу
    public int get(int index){
        isIndexExist(index);  //проверка корректности введенного индекса
        return elements[index];
    }

    //возвращает количество элементов в списке
    public int size (){
        return size;
    }

    //добавляем элемент в конец списка
    public boolean add(int value){
        if (size == elements.length){  //если в массиве места нет
            elements = increaseCapacity(); //вызываем метод, который отвечает за увеличение массива
        }
        elements[size] = value; //записываем в конец списка новое meaning
        size++;  //увеличиваем meaning переменной размера списка
        return true;
    }

    //дополнительный закрытый метод для увеличения емкости массива
    private int [] increaseCapacity(){
        int [] temp = new int[(elements.length * 2)];  //создаем новый массив большего размера
        System.arraycopy(elements, 0, temp, 0, elements.length);  //копируем в новый массив элементы из старого массива
        return temp;
    }

    //устанавливает элемент на указанную позицию
    public int set(int value, int index){
        isIndexExist(index);
        int temp = elements[index];
        elements[index] = value;
        return temp;
    }

    //переопределил метод для красивого вывода списка на экран, иначе будут выводиться значения незаполненных ячеек [1, 10] instead of [1, 10, 0, 0...]
    @Override
    public String toString(){
        int [] temp = new int[size];
        System.arraycopy(elements, 0, temp, 0, size);
        return Arrays.toString(temp);
    }

    //проверяем индексы, не выходят ли они за границы массива
    private int isIndexExist(int index){
        if (index >= size || index < 0){
            throw new IndexOutOfBoundsException("Element can't be found! "
                    + "Number of elements in array = " + size
                    + ". Total size of array = " + elements.length);
        }
        return index;
    }

    //проверяем, есть ли элементы в списке
    public boolean isEmpty(){
        return (size == 0);
    }

    //удаляем элемент по индексу
    public int remove (int index){
        isIndexExist(index);  //проверяем индекс
        int [] temp = elements;  //во временный массив заносим ссылку на текущий массив
        elements = new int [temp.length-1];  //полю elements присваиваем ссылку на новый массив размером меньше на 1
        int value = temp[index];  //сохраняем в доп. переменную meaning удаляемого element
        System.arraycopy(temp, 0, elements, 0, index);  //копируем левую часть массива до указанного индекса
        System.arraycopy(temp, index + 1, elements, index, temp.length - index - 1);  //копируем правую часть массива после указанного индекса
        size--;  //уменьшаем meaning переменной
        return value;
    }
}
List of sources used:
  1. ArrayList source code (current - JDK 12);
  2. Most of the illustrations were taken from here and some articles from JavaRush;
  3. Article on Habré .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION