Collection learning 1 - collection of love collection

Keywords: Java

;

Click me to view the tutorial: (●'◡'●)

Collections can be divided into two categories according to their storage structure:

  • Single column collection java.util.Collection
  • Double column set java.util.Map

The structure diagram is as follows:

Collection😊

Found a great blog: (. ^▽^)

Two common subclasses of the Collection interface: java.util -. List set and java.util.Set set set

Collection is the parent interface of all single column collections, so some methods common to single column collections (List and Set) are defined in collection. The method is as follows:

  • Public Boolean add (E): adds the given object to the current collection. (added after)
  • public void clear(): clear all elements in the collection.
  • Public Boolean remove (E): deletes the given object from the current collection.
  • Public Boolean contains (E): judge whether the current collection contains the given object.
  • public boolean isEmpty(): judge whether the current collection is empty.
  • public int size(): returns the number of elements in the collection.
  • public Object[] toArray(): store the elements in the collection into an array.

Method demonstration:

public static void main(String[] args) {
    // Create collection objects using polymorphic forms
    Collection<String> coll = new ArrayList<String>();
    
    // Add function Boolean add (string s)
    coll.add("Xiao Li Guang");
    coll.add("Sweeping monk");
    coll.add("Stone breaks the sky");
    System.out.println(coll); // [Xiao Li Guang, sweeping monk, stone breaking the sky]
    
    // boolean contains(E e) determines whether o exists in the set
    System.out.println("Judge whether the sweeping monk is in the collection"+coll.contains("Sweeping monk")); // true
    
    //Boolean remove (E) deletes the o element in the collection
    System.out.println(coll.remove("Stone breaks the sky")); // true
    System.out.println(coll); // [Xiao Li Guang, sweeping monk]
    
    // There are several elements in the size() collection
    System.out.println(coll.size()); // 2
    
    // Object[] toArray() is converted to an object array
    Object[] objects = coll.toArray();
    // Traversal array
    for (int i = 0; i < objects.length; i++) {
        System.out.println(objects[i]);
    }
    
    // Void clear() clears the collection
    coll.clear();
    System.out.println(coll); // []
    
    // Boolean isempty() determines whether it is empty
    System.out.println(coll.isEmpty()); // true
}

For more methods, please refer to the API

List

characteristic:

  • Element access order
  • With index (similar to array index)
  • There can be duplicate elements in the collection

Common methods:

  • public void add(int index, E element): adds the specified element to the specified position in the collection.
  • public E get(int index): returns the element at the specified position in the collection.
  • public E remove(int index): removes the element at the specified position in the list and returns the removed element.
  • public E set(int index, E element): replaces the element at the specified position in the set with the specified element, and returns the element before the update of the value.
public static void main(String[] args) {
    //Create a List collection object, polymorphic
    List<String> list = new ArrayList<>();
    
    //Use the add method to add elements to the collection
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("a");
    //Print set
    System.out.println(list);//[a, b, c, d, a] toString is not rewritten by address
    
    //public void add(int index, E element): adds the specified element to the specified position in the collection.
    list.add(3, "love");//[a, b, c, love, d, a]
    System.out.println(list);
    
    //public E remove(int index): removes the element at the specified position in the list and returns the removed element.
    String removeE = list.remove(2);
    System.out.println("Elements removed:" + removeE);//Removed element: c
    System.out.println(list);//[a, b, love, d, a]
    
    //public E set(int index, E element): replaces the element at the specified position in the set with the specified element, and returns the element before the update of the value.
    String setE = list.set(4, "A");
    System.out.println("Replaced element:" + setE);//Replaced element: a
    System.out.println(list);//[a, b, love, d, A]
    
    //There are three ways to traverse the List collection
    //Use the normal for loop
    for (int i = 0; i < list.size(); i++) {
        //public E get(int index): returns the element at the specified position in the collection.
        String s = list.get(i);
        System.out.println(s);
    }
    System.out.println("-----------------");
    
    //Using Iterators 
    Iterator<String> it = list.iterator();
    while (it.hasNext()) {
        String s = it.next();
        System.out.println(s);
    }
    System.out.println("-----------------");
    
    //Using enhanced for
    for (String s :  list) {
        System.out.println(s);
    }
    
    String r = list.get(5);//IndexOutOfBoundsException:  Index 5 out-of-bounds for length 5
    System.out.println(r);
}

LinkedList

Click me to view the tutorial: (●'◡'●)

characteristic:

  • The bottom layer is a linked list structure: slow query, fast addition and deletion
  • It contains a large number of methods to manipulate the beginning and end elements
  • Note: use the methods specific to the LinkedList collection, and polymorphism is not allowed

Common methods:

  • Public void addfirst (E): inserts the specified element at the beginning of this list.
  • Public void addlast (E): adds the specified element to the end of this list. (equivalent to add())
  • public void push(E e): push the element into the stack represented by this list. (equivalent to addFirst())
  • public E getFirst(): returns the first element of this list.
  • public E getLast(): returns the last element of this list.
  • public E removeFirst(): removes and returns the first element of this list.
  • public E removeLast(): removes and returns the last element of this list.
  • public E pop(): pop an element from the stack represented by this list. (equivalent to removeFirst())
  • public boolean isEmpty(): returns true if the list does not contain elements.
public static void main(String[] args) {
	//Create LinkedList collection object
    LinkedList<String> linked = new LinkedList<>();
    
    //Use the add method to add elements to the collection
    linked.add("a");
    linked.add("b");
    linked.add("c");
    System.out.println(linked);//[a, b, c]	
    
    //Public void addfirst (E): inserts the specified element at the beginning of this list.
    //linked.addFirst("www");
    linked.push("www");
    System.out.println(linked);//[www, a, b, c]
    
    //Public void addlast (E): adds the specified element to the end of this list. This method is equivalent to add()
    linked.addLast("com");
    System.out.println(linked);//[www, a, b, c, com]
    
    //public boolean isEmpty(): returns true if the list does not contain elements.
    //NoSuchElementException is returned if there are no elements in the collection
    if(!linked.isEmpty()){
        String first = linked.getFirst();
        System.out.println(first);//a
        String last = linked.getLast();
        System.out.println(last);//c
    }
    
     //String first = linked.removeFirst();
     String first = linked.pop();
     System.out.println("First element removed:"+first);
     String last = linked.removeLast();
     System.out.println("Last element removed:"+last);
     System.out.println(linked);//[b]
     
}

ArrayList

Click me to view the information: (●'◡'●)

characteristic:

  • In fact, it is an array that can be dynamically modified.

Common methods in ArrayList are:

  • Public Boolean add (E): adds an element to the collection. The type of the parameter is consistent with the generic type. The return value represents whether the addition is successful.
    Note: for the ArrayList collection, the add action must be successful, so the return value can be used or not.
    However, for other sets (future learning), the add action may not be successful.

  • public E get(int index): get elements from the collection. The parameter is the index number, and the return value is - the element at the corresponding position.

  • public E set(int index, e): modify an element in the set. The first is the parameter position and the second is the content to be modified.

  • public E remove(int index): deletes an element from the collection. The parameter is the index number, and the return value is the deleted element.

  • public int size(): gets the size and length of the collection. The return value is the number of elements contained in the collection.

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    System.out.println(list); // []

    // Add element to collection: add
    boolean success = list.add("Zhang San");
    System.out.println(list); // [Zhang San]
    System.out.println("Whether the added action is successful:" + success); // true

    list.add("Li Si");
    list.add("Wang Wu");
    System.out.println(list); // [Zhang San, Li Si, Wang Wu]

    // Get element from collection: get. Index value starts at 0
    String name = list.get(2);
    System.out.println("Index No. 2 position:" + name); // Wang Wu

    // Remove element from collection: remove. Index value starts at 0.
    String whoRemoved = list.remove(0);
    System.out.println("The person deleted is:" + whoRemoved); // Zhang San
    System.out.println(list); // [Zhang San, Li Si, Wang Wu]

    // Gets the length dimension of the collection, that is, the number of elements in it
    int size = list.size();
    System.out.println("The length of the collection is:" + size);
    
    // Traversal set
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}

Set

characteristic:

  • Element cannot be repeated
  • Element disorder

How Set does not allow duplicate data to be stored:

When the Set calls add(), add() will call the hashCode method and equals method of the element to judge whether the element is repeated.

HashSet

Click me to view the information: (●'◡'●)

characteristic:

  • Duplicate elements are not allowed
  • There is no index, no indexed method, and ordinary for traversal cannot be used
  • unordered set
  • The bottom layer is the hash table structure (fast query speed)
public static void main(String[] args) {
    Set<Integer> set = new HashSet<>();
    //Use the add method to add elements to the collection
    set.add(1);
    set.add(3);
    set.add(2);
    set.add(1);
    //Use iterators to traverse the set collection
    Iterator<Integer> it = set.iterator();
    while (it.hasNext()){
        Integer n = it.next();
        System.out.println(n);//1,2,3
    }
    //Traversing the set set using enhanced for
    System.out.println("-----------------");
    for (Integer i :  set) {
        System.out.println(i);
    }
}

HashCode()

Hash value: it is a decimal integer, which is randomly given by the system. It can be understood as the address value of the object, which is a simulated logical address, not the physical address of the actual data storage)

There is a method hashcode () in the Object class, which can return the hash code value of the Object. Source code: public native int hashCode();

The source code of ToString method also calls the hashCode method.

The String class overrides the hashCode method. If the contents of the two strings are the same, the call method returns the same result.

native: represents that the method calls the method of the local operating system

Hash conflict: two elements are different, but the hash value is the same

// Suppose you have a Person class at this time
// The main program of test class is as follows
public static void main(String[] args) {
    //The Person class inherits the Object class, so you can use the hashCode method of the Object class
    Person p1 = new Person();
    int h1 = p1.hashCode();
    System.out.println(h1); // 1967205423 
    Person p2 = new Person();
    int h2 = p2.hashCode();
    System.out.println(h2); // 42121758 
    
    // Hash value of string class: String class overrides hashCode method of Obejct class
    String s1 = new String("abc");
    String s2 = new String("abc");
    System.out.println(s1.hashCode());//96354
    System.out.println(s2.hashCode());//96354
}
HashCode structure for storing data

Before jdk1.8: hash table = array + linked list

Before jdk1.8: hash table = array + linked list & hash table = array + red black tree (improve query speed)

If the length of the linked list exceeds 8 bits, replace it with a red black tree to improve the query speed

HashSet stores custom type elements

The stored elements (String, Student, Person...) must override the hashCode method and the equals method

// For example, there is now a Person class with name and age attributes. People of the same name and age are required to be regarded as the same Person and can only be stored once. The rewritten hashCode method and equals method are as follows:
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
// Main program in test class
public static void main(String[] args) {
    //Create a HashSet collection to store Person
    HashSet<Person> set = new HashSet<>();
    Person p1 = new Person("Little beauty",18);
    Person p2 = new Person("Little beauty",18);
    Person p3 = new Person("Little beauty",19);
    System.out.println(p1.hashCode()); // 734175839
    System.out.println(p2.hashCode()); // 734175839
    
    set.add(p1);
    set.add(p2);
    set.add(p3);
    System.out.println(set);//[Person{name = 'little beauty', age=19}, Person{name = 'little beauty', age=18}]
}

LinkedHashSet

characteristic:

  • Is an implementation class of HashSet

  • Duplicate is not allowed

  • Element order

    The bottom layer is a hash table (array + linked list / red black tree) + linked list: one more linked list (storage order of record elements)

public static void main(String[] args) {
    HashSet<String> set = new HashSet<>();
    set.add("www");
    set.add("abc");
    set.add("abc");
    set.add("itcast");
    System.out.println(set);//[abc, www, itcast] unordered, no repetition allowed
    LinkedHashSet<String> linked = new LinkedHashSet<>();
    linked.add("www");
    linked.add("abc");
    linked.add("abc");
    linked.add("itcast");
    System.out.println(linked);//[www, abc, itcast] ordered, no repetition allowed
}

Tool class Collections 😊

Common functions

java.utils.Collections is a collection tool class used to operate on collections.

  • Public static \ < T > Boolean addall (collection \ < T > C, t... Elements): adds elements to the collection.
  • Public static void shuffle (list <? > list) disrupts the collection order.
  • Public static < T > void sort (list < T > list): sort the elements in the collection in ascending order by default.
  • Public static < T > void sort (list < T > list, comparator <? Super T >): sort the elements in the collection according to the specified rules.
public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    
    //Public static < T > Boolean addall (collection < T > C, t... Elements): add some elements to the collection.
    Collections.addAll(list,"a","b","c","d","e");
    System.out.println(list); // [a, b, c, d, e]
    
    //Public static void shuffle (list <? > list) disrupts the collection order.
    Collections.shuffle(list);
    System.out.println(list); //  [b, d, c, a, e]
    
    //Public static < T > void sort (list < T > list): sort in ascending order by default
    Collections.sort(list);
    System.out.println(list); //  [a, b, c, d, e]
}

Sorting - reparable

The premise for the use of sort (list): the elements stored in the sorted collection must implement Comparable. Override the method compareTo in the interface to define the sorting rules.

// Suppose there is a Person class, which is required to be sorted in descending order by age. The rewriting method is as follows
    @Override
    public int compareTo(Person o) {
        //return 0;// Think the elements are the same
        //Customize the comparison rules to compare the ages of two people (this parameter, Person)
        //return this.getAge() - o.getAge();// Age ascending sort
        return o.getAge() - this.getAge();//Age ascending sort
    }
// Main program of test class
public static void main(String[] args) {  
    ArrayList<Person> list03 = new ArrayList<>();
    
    list03.add(new Person("Zhang San",18));
    list03.add(new Person("Li Si",20));
    list03.add(new Person("Wang Wu",15));
    System.out.println(list03);
    //[Person{name = 'Zhang San', age=18}, Person{name = 'Li Si', age=20}, Person{name = 'Wang Wu', age=15}]
    
    Collections.sort(list03);
    System.out.println(list03);
    //[Person{name = 'Li Si', age=20}, Person{name = 'Zhang San', age=18}, Person{name = 'Wang Wu', age=15}]
}

Sort Comparator

The difference between Comparator and Comparable
Comparable: compare yourself (this) with others (parameters). You need to implement the comparable interface and rewrite the comparison rule compareTo method
Comparator: it is equivalent to finding a third-party referee and comparing two

// For example: compare the Student class. If you are the same age, compare the first word of the name
Collections.sort(list02, new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        //Sort by age in ascending order
        int result =  o1.getAge()-o2.getAge();
        //If two people are of the same age, compare them with the first word of their names
        if(result==0){
            result =  o1.getName().charAt(0)-o2.getName().charAt(0);
        }
        return  result;
    }
});
System.out.println(list02);

Variable parameters 😊

Variable parameter: a new feature after JDK1.5

Premise of use:

When the parameter list data type of the method has been determined, but the number of parameters is uncertain, variable parameters can be used

Use format: used when defining methods

Modifier return value type method name (data type... Variable name) {}

Principle of variable parameters:

The bottom layer of variable parameters is an array. Depending on the number of parameters passed, arrays of different lengths will be created to store these parameters

The number of parameters passed can be 0 (not passed), 1, 2... Or more

matters needing attention:

  • The parameter list of a method can only have one variable parameter

  • If the method has more than one parameter, the variable parameter must be written at the end of the parameter list

    public static void method(String b,double c,int d,int...a){}
    
    //Special (Ultimate) formulation of variable parameters
    public static void method(Object...obj){}
    

Code example: define a method for calculating the sum of (0-n) integers

public static int add(int...arr){
    //Define an initialized variable, record accumulation and summation
    int sum = 0;
    //Traverse the array to get each element in the array
    for (int i : arr) {
        //Cumulative summation
        sum += i;
    }
    //Return the sum result
    return sum;
}

If the number of parameters is different, arrays of different lengths will be created to store these parameters

The number of parameters passed can be 0 (not passed), 1, 2... Or more

matters needing attention:

  • The parameter list of a method can only have one variable parameter

  • If the method has more than one parameter, the variable parameter must be written at the end of the parameter list

    public static void method(String b,double c,int d,int...a){}
    
    //Special (Ultimate) formulation of variable parameters
    public static void method(Object...obj){}
    

Code example: define a method for calculating the sum of (0-n) integers

public static int add(int...arr){
    //Define an initialized variable, record accumulation and summation
    int sum = 0;
    //Traverse the array to get each element in the array
    for (int i : arr) {
        //Cumulative summation
        sum += i;
    }
    //Return the sum result
    return sum;
}

Posted by Liodel on Sun, 12 Sep 2021 14:36:16 -0700