Collection Frame Notes

Keywords: Java Back-end

aggregate

First: Set concept

The container of the object, which implements the common operations on the object, similar to the array function.

Two: Differences between sets and arrays

(1) Array length is fixed, set length is not fixed.

(2) Arrays can store basic types and reference types, and collections can only reference types.

Collection System Collection

Collection parent interface

Characteristic

Represents a set of objects of any type, out of order, without subscripts, and cannot be repeated.

Method

  • boolean add (Object obj)//Add an object.

  • boolean addAll (Collection c)//Add all objects in a collection to this collection.

  • void clear ()//Empty all objects in this collection.

  • boolean contains (Object o)//Check if this collection contains o objects.

  • boolean equals (Object o)//Compare whether this collection is equal to the specified object.

  • boolean isEmpty()//Determine if this collection is empty.

  • boolean remove (Object o)//Remove o objects from this collection.

  • int size ()//Returns the number of elements in this collection.

  • Object[] toArray()//Converts this collection to an array.

Iterators (a way specifically designed to traverse a set)

The Iterator interface provides many ways to iterate over collection elements. Each collection class includes an iteration method that returns an iterator instance.

hasNext() determines if there is a next element.

Next() Gets the next element.

remove() deletes the current element.

Use of Collection (1)

/**
 * Collection Use of interfaces
 * (1)Add Elements
 * (2)Delete element
 * (3)Traversing Elements
 * (4)judge
 */

public class Collection1 {
    public static void main(String[] args) {
        //Create a collection
        Collection collection = new ArrayList();

        //(1) Add elements
        collection.add("Apple");
        collection.add("Grape");
        collection.add("Banana");
        System.out.println("Number of elements:" + collection.size());
        System.out.println(collection);
        
        //(2) Delete elements
//        collection.remove("banana");
//        collection.clear();
//        System.out.println("Number of elements:" + collection.size()));

        //(3) Traversing Elements [Key]
        //3.1 Use enhanced for
        for (Object object : collection) {
            System.out.println(object);
        }
        //3.2 Using iterators (one way iterators specifically traverse sets)
        //hasNext(); Is there the next element
        //next(); Get the next element
        //remove(); Delete the current element
        Iterator it = collection.iterator();
        while (it.hasNext()) {
            String s = (String) it.next();
            System.out.println(s);
            //collection.remove(s); Cannot use collection delete method and concurrently modify exception
            it.remove();
        }
        System.out.println("Number of elements:" + collection.size());

        //(4) Judgment
        System.out.println(collection.contains("Banana"));//Determine if there is a banana
        System.out.println(collection.isEmpty());//Determine whether it is empty
    }
}

Use of Collection (2)

/**
 * Collection Use: Save student information
 */
public class Collection2 {
    public static void main(String[] args) {
        //New Collection Object
        Collection collection = new ArrayList();
        Student s1 = new Student("Zhang San", 20);
        Student s2 = new Student("Li Si", 21);
        Student s3 = new Student("King Five", 22);
        
        //1. Add data
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println("Number of elements:" + collection.size());
        System.out.println(collection.toString());
        
        //2. Delete data
//        collection.remove(s3);
//        collection.clear(); // empty
//        System.out.println("Number of elements:" + collection.size()));
        
        //3. Traversing data
        //3.1 Enhancement for
        for (Object object : collection) {
            Student s = (Student) object;
            System.out.println(s.toString());
        }
        //3.2 iterator: hasNext(); Next(); Remove (); collection deletion method cannot be used during iteration
        Iterator it = collection.iterator();
        while (it.hasNext()) {
            Student s = (Student) it.next();
            System.out.println(s.toString());
        }
        
        //4. Judgment
        System.out.println(collection.contains(s1));
        System.out.println(collection.isEmpty());
    }
}

/**
 * Student Class
 */
public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

List Collection

List subinterface

Characteristic

Ordered, subscripted, elements repeatable.

Method

  • void add (int index, Object o)//Insert object o at index position.

  • boolean addAll (int index, Collection c)//Add elements from a collection to the index location in this collection.

  • Object get (int index)//Returns an element in a collection at a specified location.

  • List subList (int fromIndex, int toIndex)//Returns a collection element between fromIndex and toIndex.

List Iterator

hasNext() determines if there is a next element.

hasPrevious() determines if there is a previous element.

Next() Gets the next element.

nextIndex() returns the element subscript of the next call.

Previous() gets the previous element.

previousIndex() returns the element subscript of the previous call.

remove() deletes the current element.

Use of the List interface (1)

/**
 * List Use of subinterfaces
 * Features: 1 Ordered with subscripts 2 can be repeated
 */
public class Demo01 {
    public static void main(String[] args) {
        //Create collection object first
        List list = new ArrayList<>();

        //1 Add Elements
        list.add("Apple");
        list.add("millet");
        list.add(0, "Huawei");
        System.out.println("Number of elements:" + list.size());
        System.out.println(list.toString());

        //2 Delete elements
//        list.remove("apple");
//        list.remove(0);
//        System.out.println("Number of elements:"+list.size()));
//        System.out.println(list.toString());

        //3 traversal
        //3.1 Use for traversal
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //3.2 Use enhanced for
        for (Object object : list) {
            System.out.println(object);
        }
        //3.3 Using Iterators
        Iterator it = list.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        //3.4 List Iterators, unlike Iterators, can iterate forward or backward to add, delete, and modify elements.
        ListIterator lit = list.listIterator();
        //3.4.1 Traverse from there using a list iterator
        while (lit.hasNext()) {
            System.out.println(lit.nextIndex() + ":" + lit.next());
        }
        //3.4.2 Traverse backwards and forwards using a list iterator
        while (lit.hasPrevious()) {
            System.out.println(lit.previousIndex() + ":" + lit.previous());
        }

        //4 Judgement
        System.out.println(list.contains("Apple"));
        System.out.println(list.isEmpty());

        //5 Get Position
        System.out.println(list.indexOf("Huawei"));
    }
}

Use of the List interface (2)

/**
 * List Use
 */
public class Demo02 {
    public static void main(String[] args) {
        //Create a collection
        List list = new ArrayList<>();
        //1 Add digital data (auto-boxed)
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        list.add(60);
        System.out.println("Number of elements:" + list.size());
        System.out.println(list.toString());
        
        //2 Delete operation
        //list.remove(0);
        //list.remove(list.indexOf(20));
        //list.remove((Object) 20);
        //list.remove(new Integer(20));
        System.out.println("Number of elements:" + list.size());
        System.out.println(list.toString());
        
        //3 Supplementary subList: Returns the subset, left closed right open
        List subList = list.subList(1, 3);
        System.out.println(subList.toString());
    }
}

List Common Implementation Classes

  • ArrayList:

    • Array structure, fast query, slow increase.

    • JDK1.2, fast and thread insecure.

    • Source analysis: DEFAULT_CAPACITY=10; Default capacity.

      Note: If no element is added to the collection, capacity 0, capacity 10 after adding an element.

      Each expansion is 1.5 times larger than the original.

      The elementData holds an array of elements.

      The actual number of size elements.

      add() adds an element.

          public boolean add(E e) {
              ensureCapacityInternal(size + 1);  // Increments modCount!!
              elementData[size++] = e;
              return true;
          }
      
          private void ensureCapacityInternal(int minCapacity) {
              ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
          }
      
          private void ensureExplicitCapacity(int minCapacity) {
              modCount++;
      
              // overflow-conscious code
              if (minCapacity - elementData.length > 0)
                  grow(minCapacity);
          }
      
          private void grow(int minCapacity) {
              // overflow-conscious code
              int oldCapacity = elementData.length;
              int newCapacity = oldCapacity + (oldCapacity >> 1);
              if (newCapacity - minCapacity < 0)
                  newCapacity = minCapacity;
              if (newCapacity - MAX_ARRAY_SIZE > 0)
                  newCapacity = hugeCapacity(minCapacity);
              // minCapacity is usually close to size, so this is a win:
              elementData = Arrays.copyOf(elementData, newCapacity);
          }
      
  • Vertor:

    • Array structure, fast query, slow increase.

    • JDK1.0, running slowly and thread-safe.

  • Linked List:

    • Chain list structure is implemented, which increases or deletes quickly and queries are slow.

    • Source analysis:

      int size: The size of the collection.

      Node first; Head node of the chain table.

      Node last; The end node of the chain table.

          private void linkFirst(E e) {
              final Node<E> f = first;
              final Node<E> newNode = new Node<>(null, e, f);
              first = newNode;
              if (f == null)
                  last = newNode;
              else
                  f.prev = newNode;
              size++;
              modCount++;
          }
      
          private static class Node<E> {
              E item;
              Node<E> next;
              Node<E> prev;
      
              Node(Node<E> prev, E element, Node<E> next) {
                  this.item = element;
                  this.next = next;
                  this.prev = prev;
              }
          }
      

Use of ArrayList

/**
 * ArrayList Use
 * Storage structure: Array, fast lookup traversal, slow growth
 */
public class Demo03 {
    public static void main(String[] args) {
        //Create a collection
        ArrayList arrayList = new ArrayList();

        //1 Add Elements
        Student s1 = new Student("Lau Andy", 22);
        Student s2 = new Student("Guo Fucheng", 21);
        Student s3 = new Student("Jay Chou", 18);
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println("Number of elements:" + arrayList.size());
        System.out.println(arrayList.toString());

        //2 Delete elements
//        arrayList.remove(s1);
//        System.out.println("Number of elements:"+arrayList.size()));

        //3 Traverse Elements [Focus]
        //3.1 Using Iterators
        Iterator it = arrayList.iterator();
        while (it.hasNext()) {
            Student student = (Student) it.next();
            System.out.println(student.toString());
        }
        //3.2 List Iterator
        ListIterator lit = arrayList.listIterator();
        while (lit.hasNext()) {
            Student student = (Student) lit.next();
            System.out.println(student.toString());
        }
        while (lit.hasPrevious()) {
            Student student = (Student) lit.previous();
            System.out.println(student.toString());
        }

        //4 Judgement
        System.out.println(arrayList.contains(s1));
        System.out.println(arrayList.isEmpty());

        //5 Find
        System.out.println(arrayList.indexOf(s1));
    }
}

Use of Vector

/**
 * Vector Use of collections
 * Storage structure: array
 */
public class Demo04 {
    public static void main(String[] args) {
        //Create a collection
        Vector vector = new Vector<>();

        //1 Add Elements
        vector.add("Strawberry");
        vector.add("Apple");
        vector.add("Banana");
        System.out.println("Number of elements:" + vector.size());

        //2 Delete elements
//        vector.remove(0);
//        vector.remove("watermelon");
//        vector.clear();

        //3 Traverse Elements
        //Use enumerator
        Enumeration en = vector.elements();
        while (en.hasMoreElements()) {
            String o = (String) en.nextElement();
            System.out.println(o);
        }

        //4 Judgement
        System.out.println(vector.contains("Strawberry"));
        System.out.println(vector.isEmpty());

        //5vector Other Methods
        //firstElement,lastElement,elementAt();
    }
}

Use of LinkedList

/**
 * LinkedList Use
 * Storage structure: two-way list
 */
public class Demo05 {
    public static void main(String[] args) {
        //Create a collection
        LinkedList linkedList = new LinkedList<>();

        //1 Add Elements
        Student s1 = new Student("Lau Andy", 22);
        Student s2 = new Student("Guo Fucheng", 21);
        Student s3 = new Student("Jay Chou", 18);
        linkedList.add(s1);
        linkedList.add(s2);
        linkedList.add(s3);
        System.out.println("Number of elements:" + linkedList.size());
        System.out.println(linkedList.toString());

        //2 Delete elements
//        linkedList.remove(s1);
//        System.out.println("Number of elements:"+linkedList.size()));
//        linkedList.clear();

        //3 Traverse Elements
        //3.1for traversal
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }
        //3.2 Enhancement for
        for (Object object : linkedList) {
            Student s = (Student) object;
            System.out.println(s.toString());
        }
        //3.3 Using Iterators
        Iterator it = linkedList.iterator();
        while (it.hasNext()) {
            Student s = (Student) it.next();
            System.out.println(s.toString());
        }
        ListIterator lit = linkedList.listIterator();
        while (lit.hasNext()) {
            Student s = (Student) lit.next();
            System.out.println(s.toString());
        }

        //4 Judgement
        System.out.println(linkedList.contains(s1));
        System.out.println(linkedList.isEmpty());

        //5 Get (position of collection in element)
        System.out.println(linkedList.indexOf(s2));
    }
}

Generic

  • Java generics are a new feature introduced in JDK 1.5, which is essentially parameterized types, passing types as parameters.

  • Common forms are generic classes, generic interfaces, and generic methods.

  • Syntax: <T...> T is called a type placeholder and represents a reference type.

  • Benefits: (1) Improve code reuse.

    (2) Prevent type conversion exceptions and improve code security.

generic class

/**
 * generic class
 * Syntax: Class name <T>
 * T Is a type placeholder that represents a reference type, if you write more than one separated by commas
 */
public class MyGeneric<T> {
    //Using generic T
    //1 Create variable
    T t;

    //2 Generics as method parameters
    public void show(T t) {
        System.out.println(t);
    }

    //3 Generics as return values of methods
    public T getT() {
        return t;
    }
}
public class TestGeneric {
  public static void main(String[] args) {
      //Creating objects using generic classes
      //Note: 1 Generics can only use reference types. 2 Different generic objects cannot be assigned to each other.
      MyGeneric<String> myGeneric = new MyGeneric<>();
      myGeneric.t = "hello";
      myGeneric.show("Hello everyone,Come on.");
      String string = myGeneric.getT();
      System.out.println(string);

      MyGeneric<Integer> myGeneric2 = new MyGeneric<>();
      myGeneric2.t = 100;
      myGeneric2.show(200);
      Integer integer = myGeneric2.getT();
      System.out.println(integer);
  }
}

generic interface

/**
 * generic interface
 * Syntax: Interface name <T>
 * Note: You cannot create static constants using generics
 *
 * @param <T>
 */
public interface MyInterface<T> {
    String name = "Zhang San";

    T Server(T t);
}
public class MyInterfaceImpl implements MyInterface<String>{

    @Override
    public String Server(String t) {
        System.out.println(t);
        return t;
    }
}
public class MyInterfaceImpl2<T> implements MyInterface<T> {

    @Override
    public T Server(T t) {
        System.out.println(t);
        return t;
    }
}
        MyInterfaceImpl impl=new MyInterfaceImpl();
        impl.Server("xxxxxx");

        MyInterfaceImpl2<Integer> impl2=new MyInterfaceImpl2<>();
        impl2.Server(1000);

generic method

/**
 * generic method
 * Syntax: <T>Return value type
 */

public class MyGenericMethod {
    //generic method
    public <T> T show(T t) {
        System.out.println("generic method" + t);
        return t;
    }
}
        MyGenericMethod myGenericMethod = new MyGenericMethod();
        myGenericMethod.show("Come on.");
        myGenericMethod.show(200);
        myGenericMethod.show(3.14);

Generic Set

  • Probability: A parameterized type, a type-safe set, and a mandatory set element must have the same type.
  • Characteristic:
    • Check at compile time instead of throwing exceptions at run time.
    • There is no need for type conversion (unboxing) when accessing.
    • References between different generics cannot be mutually assigned, and there is no polymorphism in the generic.
public class Demo01 {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("xxx");
        arrayList.add("zzz");

        for (String s : arrayList) {
            System.out.println(s);
        }

        ArrayList<Student> arrayList2 = new ArrayList<>();
        Student s1 = new Student("Lau Andy", 22);
        Student s2 = new Student("Guo Fucheng", 21);
        Student s3 = new Student("Jay Chou", 18);
        arrayList2.add(s1);
        arrayList2.add(s2);
        arrayList2.add(s3);

        Iterator<Student> it = arrayList2.iterator();
        while (it.hasNext()) {
            Student student = it.next();
            System.out.println(student.toString());
        }
    }
}

Set Collection

Set Subinterface

  • Features: Unordered, no subscripts, elements are not repeatable.
  • Method: All inherits from methods in Collection.

Set Implementation Class

  • HashSet
    • Calculate element storage location based on HashCode.
    • When the hash codes stored in the elements are the same, equals is called to confirm, and if the result is true, the latter is rejected.
  • TreeSet:
    • Implement elements not to repeat based on permutation order.
    • The SortedSet interface is implemented to automatically sort collection elements.
    • The type of element object must implement the Comparable interface, specifying the collation.
    • The CompareTo method determines if it is a duplicate element.

Use of Set interface

/**
 * Test Set Interface Usage
 * Features: (1) Unordered, no subscript (2) Cannot repeat
 */
public class Demo01 {
    public static void main(String[] args) {
        //Create a collection
        Set<String> set = new HashSet<>();

        //1 Add data
        set.add("millet");
        set.add("Apple");
        set.add("Huawei");
        System.out.println("Number of elements:" + set.size());
        System.out.println(set.toString());

        //2 Delete data
//        set.remove("apple");
//        System.out.println(set.toString());

        //3 Traverse data [Key]
        //3.1 Enhancement for
        for (String string : set) {
            System.out.println(string);
        }
        //3.2 Using Iterators
        Iterator it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        
        //4 Judgement
        System.out.println(set.contains("Huawei"));
        System.out.println(set.isEmpty());
    }
}

Use of HashSet (1)

/**
 * HashSet Use of collections
 * Storage structure: Hash table (array + Chain Table + red-black tree)
 */
public class Demo02 {
    public static void main(String[] args) {
        //Create a collection
        HashSet<String> hashSet = new HashSet<>();

        //1 Add Elements
        hashSet.add("Jay Chou");
        hashSet.add("Edison Chan");
        hashSet.add("Zhou Huimin");
        hashSet.add("Wang Zuxian");
        System.out.println("Number of elements:" + hashSet.size());
        System.out.println(hashSet.toString());

        //2 Delete elements
        hashSet.remove(0);
        System.out.println("Number of elements:" + hashSet.size());

        //3 Traverse Elements
        //3.1 Enhancement for
        for (String string : hashSet) {
            System.out.println(string);
        }
        //3.2 Iterator
        Iterator<String> it = hashSet.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        
        //4 Judgement
        System.out.println(hashSet.contains("Wang Zuxian"));
        System.out.println(hashSet.isEmpty());
    }
}

Use of HashSet (2)

/**
 * Human beings
 */
public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        if (this.name.equals(person.getName())&&this.age== person.getAge()){
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
/**
 * HashSet Use
 * Storage structure: Hash table (array + Chain Table + red-black tree)
 * Stored Procedures (Repeat by)
 * (1)Calculate the saved location based on hashcode, save it directly if it is empty, and perform the second step if it is not empty.
 * (2)Then execute the equals method. If the equals method is true, it is considered duplicate. Otherwise, it forms a list.
 */
public class Demo03 {
    public static void main(String[] args) {
        //Create a collection
        HashSet<Person> hashSet=new HashSet<>();

        //1 Add data
        Person p1 = new Person("Wang Zuxian",18);
        Person p2 = new Person("Zhou Huimin",24);
        Person p3 = new Person("Jay Chou",20);
        hashSet.add(p1);
        hashSet.add(p2);
        hashSet.add(p3);
        hashSet.add(new Person("Jay Chou",20));
        System.out.println("Number of elements:"+hashSet.size());
        System.out.println(hashSet.toString());

        //2 Delete data
//        hashSet.remove(p1);
//        System.out.println("Number of elements:"+hashSet.size()));

        //3 Traverse data
        //3.1 Use enhanced for
        for (Person person:hashSet) {
            System.out.println(person);
        }
        //3.2 Iterator
        Iterator<Person> it= hashSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }

        //4 Judgement
        System.out.println(hashSet.contains(new Person("Jay Chou",20)));
        System.out.println(hashSet.isEmpty());
    }
}

Use of TreeSet (1)

/**
 * TreeSet Use
 * Storage structure: red and black trees
 */
public class Demo04 {
    public static void main(String[] args) {
        //Create a collection
        TreeSet<String> treeSet = new TreeSet<>();

        //1 Add Elements
        treeSet.add("xyz");
        treeSet.add("abc");
        treeSet.add("hello");
        treeSet.add("xyz");//Duplicate no longer added
        System.out.println("Number of elements:" + treeSet.size());
        System.out.println(treeSet.toString());

        //2 Delete elements
        treeSet.remove("xyz");
        System.out.println("Number of elements:" + treeSet.size());

        //3 Traverse Elements
        //3.1 Enhancement for
        for (String string : treeSet) {
            System.out.println(string);
        }
        //3.2 Iterator
        Iterator<String> it = treeSet.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        //4 Judgement
        System.out.println(treeSet.contains("xyz"));
        System.out.println(treeSet.isEmpty());
    }
}

Use of TreeSet (2)

public class Person implements Comparable<Person> {    
    //First by name, then by age
    @Override
    public int compareTo(Person o) {
        int n1 = this.getName().compareTo(o.getName());
        int n2 = this.age - o.getAge();

        return n1==0?n2:n1;
    }
}
/**
 * Save data using TreeSet
 * Storage structure: red and black trees
 * Requirement: The element must implement the Comparable interface, and the compareTo() method returns a value of 0, which is considered a duplicate element
 */
public class Demo05 {
    public static void main(String[] args) {
        //Create a collection
        TreeSet<Person> treeSet = new TreeSet<>();

        //1 Add data
        Person p1 = new Person("xyz", 18);
        Person p2 = new Person("hello", 24);
        Person p3 = new Person("abc", 20);
        Person p4 = new Person("abc", 22);
        treeSet.add(p1);
        treeSet.add(p2);
        treeSet.add(p3);
        treeSet.add(p4);
        System.out.println("Number of elements:" + treeSet.size());
        System.out.println(treeSet.toString());

        //2 Delete data
        treeSet.remove(p1);
        System.out.println("Number of elements:" + treeSet.size());

        //3 Traverse data
        //3.1 Enhancement for
        for (Person person : treeSet) {
            System.out.println(person);
        }
        //3.2 Iterator
        Iterator<Person> it = treeSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }

        //4 Judgement
        System.out.println(treeSet.contains(p1));
        System.out.println(treeSet.isEmpty());
    }
}

Comparator interface

/**
 * TreeSet Use of collections
 * Comparator: Implement custom comparisons (comparators)
 * Comparable: Comparable
 */
public class Demo06 {
    public static void main(String[] args) {
        //Create a collection and specify comparison rules
        TreeSet<Person> treeSet=new TreeSet<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int n1=o1.getAge()-o2.getAge();
                int n2=o1.getName().compareTo(o2.getName());

                return n1==0?n2:n1;
            }
        });

        Person p1 = new Person("xyz", 18);
        Person p2 = new Person("hello", 24);
        Person p3 = new Person("abc", 20);
        Person p4 = new Person("cba", 20);

        treeSet.add(p1);
        treeSet.add(p2);
        treeSet.add(p3);
        treeSet.add(p4);

        System.out.println(treeSet.toString());

    }
}

TreeSet case

/**
 * Requirements: Use the TreeSet collection to sort strings by length
 * Comparator Interface implementation custom comparison
 */
public class Demo07 {
    public static void main(String[] args) {
        //Create a collection and specify comparison rules
        TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int n1 = o1.length() - o2.length();
                int n2 = o1.compareTo(o2);
                return n1 == 0 ? n2 : n1;
            }
        });
        //Add data
        treeSet.add("one");
        treeSet.add("lisi");
        treeSet.add("cat");
        treeSet.add("zhangsan");
        treeSet.add("chongqing");
        System.out.println(treeSet.toString());
    }
}

Map Collection

Map parent interface

Characteristic

Stores a pair of data (Key-Value), out of order, without subscripts, keys that are not duplicated, and values that are duplicated.

Method

  • V put (K key,V value)//Store objects in a collection, key values. Repeated key overrides the original value.
  • Object get (Object key)//Get the corresponding value based on the key.
  • keySet //Returns all key s.
  • Collection values ()//Returns a Collection collection containing all values.
  • EnySet<Map.Entry<K, V>//Key value matching Set set.

EnySet is more efficient than keySet.

Map interface use

/**
 * Map Use of interfaces
 * Features: (1) Stored key-value pairs (2) Keys cannot be duplicated, values can be duplicated (3) Unordered
 */
public class Demo01 {
    public static void main(String[] args) {
        //Create Map Collection
        Map<String, String> map = new HashMap<>();
        //1 Add Elements
        map.put("cn", "China");
        map.put("uk", "Britain");
        map.put("usa", "U.S.A");
//        map.put("cn","zhongguo"); Later addition does not increase the number of elements, but replaces the value value.

        System.out.println("Number of elements:" + map.size());
        System.out.println(map.toString());

        //2 Delete elements
//        map.remove("usa");
//        System.out.println("Number of elements:"+map.size()));

        //3 Traverse Elements
        //3.1 Use keySet ()
        //Set<String> keyset = map.keySet();
        for (String key : map.keySet()) {
            System.out.println(key + "-" + map.get(key));
        }
        //3.2 Use entrySet() Map.Entry mapping pairs (key-value pairs)
        //Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "-" + entry.getValue());
        }

        //4 Judgement
        System.out.println(map.containsKey("cn"));
        System.out.println(map.containsValue("Thailand"));
    }
}

HashMap uses

  • HashMap

    • JDK1.2, thread insecurity, fast running; Allow null as key or value.
  • Hashtable:

    • JDK1.0, thread-safe and slow; null is not allowed as key or value.
  • Properties:

    • A subclass of Hashtable that requires both key and value to be String. Usually used for reading configuration files.
  • TreeMap:

    • Implements the SortedMap interface, a subinterface of Map, which automatically sorts key s.

    HashMap (): Construct an empty HashMap with a default initial capacity (16) and a default load factor (0.75).

package Map Study;

public class Student implements Comparable<Student>{
    private String name;
    private int stuNo;

    public Student() {
    }

    public Student(String name, int stuNo) {
        this.name = name;
        this.stuNo = stuNo;
    }

    public String getName() {
        return name;
    }

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

    public int getStuNo() {
        return stuNo;
    }

    public void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }

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

    @Override
    public int compareTo(Student o) {
        int n1=this.stuNo-o.getStuNo();
        return n1;
    }
}
/**
 * HashMap Use of collections
 * Storage structure: Hash table (array + Chain Table + red-black tree)
 * Use key s to hashcode and equals as duplicates
 */
public class Demo02 {
    public static void main(String[] args) {
        //Create a collection
        //Save space by not adding the element table=null size=0 after just creating hashmap
        HashMap<Student, String> students = new HashMap<Student, String>();

        //1 Add Elements
        Student s1 = new Student("Sun WuKong", 100);
        Student s2 = new Student("Zhu Bajie", 101);
        Student s3 = new Student("Sand Monk", 102);
        students.put(s1, "Chongqing");
        students.put(s2, "Shanghai");
        students.put(s3, "Beijing");
        //students.put(s3,'Nanjing');
        System.out.println("Number of elements:" + students.size());
        System.out.println(students.toString());

        //2 Delete
//        students.remove(s1);
//        System.out.println("Number of elements:"+students.size()));

        //3 traversal
        //3.1 Use keySet ()
        for (Student key : students.keySet()) {
            System.out.println(key.toString() + "-" + students.get(key));
        }
        //3.2 Use entrySet()
        for (Map.Entry<Student, String> entry : students.entrySet()) {
            System.out.println(entry.getKey() + "-" + entry.getValue());
        }

        //4 Judgement
        System.out.println(students.containsKey(s1));
        System.out.println(students.containsValue("Chongqing"));
    }
}

HashMap Source Analysis

Source Code Analysis

1 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//hashMap initial capacity size
2 static final int MAXIMUM_CAPACITY = 1 << 30;//Maximum Array Capacity for hashMap
3 static final float DEFAULT_LOAD_FACTOR = 0.75f;//Default Load Factor
4 static final int TREEIFY_THRESHOLD = 8;//jdk1.8 Adjust to red-black tree when chain length is greater than 8
5 static final int UNTREEIFY_THRESHOLD = 6;//jdk1.8 Adjust to chain list when chain length is less than 6
6 static final int MIN_TREEIFY_CAPACITY = 64;//jdk1.8 Adjusts to a red-black tree when the chain length is greater than 8 and the number of collection elements is greater than or equal to 64
7 transient Node<K,V>[] table;//Arrays in Hash Table
8 size;//Number of elements

Parametric construction

public HashMap(){
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

put method

public V put(K key,V value){
    return putVal(hash(key),key,value,false.true);
}

summary

(1)HashMap When first created,table say null,To save space,When adding the first element is,table Capacity adjustment to 16
(2)When the number of elements is greater than the threshold (16)*0.75=12)time,It will be expanded to twice its original size. Purpose: Reduce the number of adjustment elements
(3)jdk1.8 When the length of each chain table is greater than 8 and the number of elements in the set is greater than or equal to 64, it is adjusted to a red-black tree to improve the efficiency of execution.
(4)jdk1.8 Adjust to chain list when chain length is less than 6
(5)jdk1.8 Previously, headers were inserted in the list. jdk1.8 Later is tail insert

Use of TreeMap

/**
 * TreeMap Use
 * Storage structure: red and black trees
 */
public class Demo03 {
    public static void main(String[] args) {
        //Create a collection
        TreeMap<Student,String> treeMap=new TreeMap<Student,String>();

        //1 Add Elements
        Student s1 = new Student("Sun WuKong", 100);
        Student s2 = new Student("Zhu Bajie", 101);
        Student s3 = new Student("Sand Monk", 102);
        treeMap.put(s1, "Chongqing");
        treeMap.put(s2, "Shanghai");
        treeMap.put(s3, "Beijing");
        System.out.println("Number of elements:"+treeMap.size());
        System.out.println(treeMap.toString());

        //2 Delete
//        treeMap.remove(s3);
//        System.out.println(treeMap.size());

        //3 traversal
        //3.1 Use keySet
        for (Student key : treeMap.keySet()) {
            System.out.println(key+"-"+treeMap.get(key));
        }
        //3.2 Use entryKey
        for (Map.Entry<Student,String> entry: treeMap.entrySet()) {
            System.out.println(entry.getKey()+"-"+entry.getValue());
        }

        //4 Judgement
        System.out.println(treeMap.containsKey(s1));
    }
}

Collections Tool Class

  • Concepts: Collection tool classes that define common methods of collections other than access.
  • Method:
    • Public static void reverse (List<?> list)//Reverse the order of elements in a collection
    • Public static void shuffle (List<?> list) //Randomly reset the order of collection elements
    • public static void sort(List list)//ascending sort (element type must implement Comparable interface)

Collection Summary

  • Concepts of sets:
    • Containers for objects, similar to arrays, define common methods for manipulating multiple objects.
  • List collection:
    • Ordered, subscripted, elements repeatable. (ArrayList, LinkenList, Vertor)
  • Set collection:
    • Unordered, no subscripts, elements are not repeatable. (HashSet, TreeSet)
  • Map Collection:
    • Stores a pair of data, out of order, without subscripts, keys that are not duplicated, and values that are duplicated. (HashMap, HashTable, TreeMap)
  • Collections:
    • A collection tool class that defines common methods for collections other than access.

Posted by alexscan on Tue, 02 Nov 2021 09:38:01 -0700