Collection framework summary:

 //Iterator traversal
        Iterator iterator = hashSet.iterator();//Get iterator object order: subscript
        while (iterator.hasNext()){//Determine whether the specified can be moved
            Object next = iterator.next();//Specifies to move and get the current element
            System.out.println(next);
        }

1.4.1 add operation

1.1 contents

1. Why use collections?
2. What are the collection architectures?
3. List set
4. ArrayList set
5. LinkedList set.
6. Set set
7. HashSet set
8. TreeSet set.
9. Map
10.HashMap set.
11.TreeMap set.

1.2 why use collections?

1. We used to study arrays

Thinking: is the array defective-- Constant volume [if a certain array is defined, their length cannot be changed.] If you need to change the length of the array, it becomes very complex.

2. Can we define a container with changed length--- Certainly.

3. Tear containers of variable length by hand.

public class MyArray {

     private Object [] arr; // Declare an array of type object
     private int size;// Indicates the subscripts of the array because they are class members. Variables have default values when creating objects.


public MyArray() {/ / parameterless constructor
            this(3); / / other constructors in this class are objects of this class. If this() is in the constructor, it means calling other constructors of this class
     }

public MyArray(int initSize) {/ / parameterized constructor -- indicates the length of the array
If (initsize < 0) {/ / illegal length
Throw new runtimeException ("the length of the sorry array is wrong.");
          }
          arr=new Object[initSize];
     }

/ / put element o into array arr
     public void addData(Object o){
/ / judge whether your array is full
           if(size>=arr.length){
/ / capacity expansion -- (1) the length of the container becomes longer (2) copy the elements in the original container to the new container
               Object[] newArr = Arrays.copyOf(arr, size * 2);
               arr=newArr;
           }
           arr[size]=o;
           size++;
     }

/ / get the elements in the array according to the subscript.
     public Object getData(int index){
            if(index>=size){
throw new ArrayIndexOutOfBoundsException("subscript out of bounds");
            }
           Object o = arr[index];
            return o;
     }


}

Based on this idea that the frame can be torn by hand,

java official website creates multiple classes based on arrays according to different data structures, and these classes are collectively referred to as collection framework.

Later, when we talk about the collection framework, we will represent multiple classes.

1.3 architecture of collection

 

1.4 List set - ArrayList

1.4.0 creating collection objects

List list = new ArrayList(); //Create a collection object. If the length of the collection container is not specified, the default is 10

   List list1 = new ArrayList(15); //Create a collection object and specify that the length of the collection container is 15
  //Add (1) any type can be added
        list.add("java01");//Add string
        list.add("java02");
        list.add(15.5);//Add decimal
        list.add(18);//Add integer
        list.add(true);//Add Boolean
        list.add(new Date());//Add date
        System.out.println(list);//Display all objects in the list
        list.add(2,"hello"); //Add an element where the subscript is 2 and shift the following element
        System.out.println(list); //toString() is called by default when printing an object

        List list2=new ArrayList();
        list2.add("a");
        list2.add("b");

        list.addAll(list2);//Add multiple elements and add each element in list2 to the list one by one
        System.out.println(list);

1.4.2 deleting

 //Delete operation
        list.remove(2);//Remove element with subscript 2
        System.out.println(list);//Displays the elements in the collection
        list.clear();//Empty the elements in the collection
        System.out.println(list);//Displays the elements in the collection

1.4.3 modification

  //Modify operation
        list.set(1,"Lau Andy");//Modify the element with subscript 1 to "Andy Lau" string
        System.out.println(list);

 

1.4.4 query operation

       List list = new ArrayList();
        list.add("java01");
        list.add("java02");
        list.add("java03");
        list.add("java02");

        //Query method
        Object o = list.get(1);//Get elements from Subscripts
        System.out.println(o);

        int size = list.size();//Gets the number of elements in the collection.
        System.out.println(size);

        boolean f = list.contains("java05");//Determine whether the element is in the collection
        System.out.println(f);

        int index = list.indexOf("java05");//The first occurrence of a query element in a collection
        System.out.println(index);

        //Loop through the elements in the collection
        for(int i=0;i<list.size();i++){
            Object o1 = list.get(i);
            System.out.println(o1);
        }

1.4.5 ArrayList underlying source code

Start with the construction method. new ArrayList(22) The underlying layer declares a Object Array name of type elementData
  Object[] elementData

  public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) { //Greater than 0
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) { //Equal to initializing to an empty array
            this.elementData = EMPTY_ELEMENTDATA;
        } else { //Throw an exception 
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

==========add("java01")======E Understood as Object type================  
   public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Capacity expansion 
        elementData[size++] = e;  //Assign the element to the corresponding position of the array
        return true;
    }
==========indexOf("java02") Determine the first position of an element in the collection=============
     public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i])) //And the contents of each element in the array
                    return i;  //Returns the position of an element in a collection
        }
        return -1;
    }   

===========size() Length of request array======================
 public int size() {
        return size;
    }   

============contain("java05")Determine whether the element is in the collection==============
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
===============get(1) Gets the element at the specified location========
   public E get(int index) {
        rangeCheck(index); //Judge whether the specified location is legal 

        return elementData(index);
    }  

    E elementData(int index) {
        return (E) elementData[index];
    } 

============toString() Why not print the reference address of the object 
    [java01, java02, java03, java02]Because it was rewritten Object Inside toString method.
    
 public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }   

Through the analysis of the underlying code of ArrayList method: the underlying is the operation of array.
The bottom layer of ArrayList is implemented based on array.

1.5 LinkedList

It is a linked list structure.

1.5.1 delete

 //Delete operation
        linkedList.removeFirst();//Remove header element
        System.out.println(linkedList);

        linkedList.remove(2);//Removes the element at the specified location
        System.out.println(linkedList);

        linkedList.removeLast();//Remove trailing elements
        System.out.println(linkedList);

1.5.2 add / / add
      

//add to
        linkedList.add("java01"); //Append tail
        linkedList.addFirst("java02"); //Add to header
        linkedList.addLast("java03");//Append to tail
        linkedList.addFirst("java04"); //Append to header
        linkedList.addLast("java05");//Append to tail
        System.out.println(linkedList);

1.5.3 modification

 //Modify operation
        linkedList.set(1,"java11");
        System.out.println(linkedList);

1.5.4 query operation

 //Query operation
        int size = linkedList.size();//Find length
        boolean empty = linkedList.isEmpty();//Is it empty

        boolean b = linkedList.contains("java01");//Determine whether the element is in the collection

        Object o = linkedList.get(1);//Gets the element at the specified location according to the subscript

        Object first = linkedList.getFirst();//Get the first element
        System.out.println(first);

        Object last = linkedList.getLast();
        System.out.println(last);

2.0 underlying source code of LinkedList

1,==================== get(1)-----Get element========================
   public E get(int index) {
        checkElementIndex(index); //Check that the index subscript is correct.
        return node(index).item;  //Li Si Node object
    }
 ========================node(index)=============================
 Node<E> node(int index) {
        //>>Bit operation binary operation ----- size > > 1 half means size/2
        if (index < (size >> 1)) { //First half
            Node<E> x = first; 
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {  //Second half
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

.

Analysis: LinkedList query is inefficient. Because it needs to look back one node at a time.

3. Set set

 

 

3.1 HashSet set

3.1.1 create a HashSet object.

public class Test02 {
    public static void main(String[] args) {
        HashSet  hashSet= new HashSet();

        HashSet  hashSet1 = new HashSet(16);//Initial container size

        //LoadFactor: --- > 0.7f indicates that the load factor requires capacity expansion when the space is 70%
        HashSet hashSet2 = new HashSet(16,0.7f);
    }
}

3.1.2 adding elements

 //Add operation
        hashSet.add("java01");
        hashSet.add("java02");
        hashSet.add("java04");
        hashSet.add("java03");
        hashSet.add("java02");

        HashSet set2=new HashSet();
        set2.add("Lau Andy");
        set2.add("Xue You Zhang");
        set2.add("dawn");
        
        hashSet.addAll(set2); //Add each element in set2 to hashset
        System.out.println(hashSet); //Elements cannot be repeated and out of order

3.1.3 deletion

 //delete
        hashSet.remove("dawn");//Because it is out of order, it cannot be deleted by subscript
        hashSet.clear();//Empty container collection
        System.out.println(hashSet);

3.1.4 modification

 

  //Modify operation
        boolean empty = hashSet.isEmpty(); //Judge whether it is empty
        System.out.println(empty);

        boolean b = hashSet.contains("Lau Andy");//Determine whether the element is in the container
        System.out.println(b);

3.1.5 traversal of HashSet

(1) Traversal by iterator (2) traversal by for each

 //Iterator traversal
        Iterator iterator = hashSet.iterator();//Get object subscript: ordered iterator
        while (iterator.hasNext()){//Determine whether the specified can be moved
            Object next = iterator.next();//Specifies to move and get the current element
            System.out.println(next);
        }
 //Traversal --- foreach
        for(Object o: hashSet){
            System.out.println(o);
        }

 

3.1.6 source code of HashSet

Let's start with constructors:
    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }
 Creating a HashSet The underlying object is created HashMap. 

3.2 TreeSet set.

As like as two peas in HashSet, the methods in TreeSet are just different from their implementations.
TreeSet is implemented based on TreeMap. TreeSet can realize the ordered set, but the ordering needs to be realized through the comparator.

Example: store String type.

TreeSet treeSet=new TreeSet();
        treeSet.add("java05");
        treeSet.add("java03");
        treeSet.add("java04");
        treeSet.add("java01");
        treeSet.add("java02");
        treeSet.add("java04");

        System.out.println(treeSet);

Store an object type:

public class Test04 {
    public static void main(String[] args) {
        TreeSet treeSet=new TreeSet();
        treeSet.add(new Student("Juen-Kai Wang",17));
        treeSet.add(new Student("Zhao Xiaopu",16));
        treeSet.add(new Student("Zhao Juntao",16));
        treeSet.add(new Student("Yan Keqi",15));

        System.out.println(treeSet);
    }
}

Discovery: Elements in TreeSet must implement the Comparable interface before they can be put into TreeSet

There are two solutions:

First: let your class implement the Comparable interface

public class Test04 {
    public static void main(String[] args) {
        TreeSet treeSet=new TreeSet(); //TreeSet does not allow duplicate elements
        treeSet.add(new Student("Juen-Kai Wang",17));
        treeSet.add(new Student("Zhaoxiaopu",16));
        treeSet.add(new Student("Zhao Juntao",16));
        treeSet.add(new Student("Yan Keqi",15));

        System.out.println(treeSet);
    }
}
class Student implements Comparable{
     private String name;
     private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
   //Sorting: -- if it is greater than 0, the current element is larger than o. if it is - 1, the currently added element is smaller than o. if it is 0, the same element is returned.
    @Override
    public int compareTo(Object o) {
        Student student= (Student) o;
        System.out.println(this+"===================>"+o);

        if(this.age>student.age){
            return 1;
        }
        if(this.age<student.age){
            return -1;
        }

        return 0;
    }
}

Second: specify the sorted objects when creating TreeSet.

Tags: Java

Posted by bernouli on Mon, 18 Apr 2022 13:36:30 +0930