Java collection framework

catalogue

Concept of set

Collection interface

1.Collection parent interface

2. Use iterators to traverse the collection

List interface and implementation class

1. List iterator

2.List interface implementation class

Generics and utility classes

⚠️ be careful

1. Generic class

2. Generic interface

3. Generic methods

4. Generic collection

Set interface and implementation class

1.Hashset

2.TreeSet

3.Comparator interface

Map interface and implementation class

1.Map parent interface

2.HashMap

3.TreeMap

4.Collections tool class

Concept of set

Object, which defines common methods for operating multiple objects. The function of array can be realized.

Difference between and array:

  1. The array length is fixed and the collection length is not fixed

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

Collection interface

1.Collection parent interface

  • Features: it represents a group of objects of any type. It is unordered, subscript free and cannot be repeated

  • method:

    • boolean add(Object obj): add an object

    • boolean addAll(Collection c): adds all objects in a collection to this collection

    • void Clear(): clear all objects in this collection

    • boolean contains(Object o): check whether there are o objects in this collection

    • boolean equals(Object o): compares whether this collection is equal to the specified object

    • boolean isEmpty(): judge whether this collection is empty

    • boolean remove(Object o): removes o objects from this collection

    • int size(): returns the number of elements in the collection

    • Object [] toArray(): convert this collection to an array

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
​
public class Demo01 {
   //Use of Collection interface
   //1. Add elements
   //2. Delete element
   //3. Traverse elements
   //4. Judgment
   public static void main(String[] args) {
       //Create collection
       Collection conllection=new ArrayList();
       //Add element
       conllection.add("apple");
       conllection.add("orange");
       conllection.add("banana");
       System.out.println("Number of elements"+conllection.size());
       System.out.println(conllection);
       //Delete element
       conllection.remove("apple");
       System.out.println(conllection);
       //Traversal element [key]
       //Use enhanced for to traverse the collection (enhanced for does not require subscripts)
       for(Object obj:conllection){
           System.out.println(obj);
      }
​
       //Use iterators (methods designed to iterate over or traverse collections)
       Iterator it=conllection.iterator();
       while(it.hasNext()){
           String object=(String)it.next();
           System.out.println(object);
           //The collection deletion method cannot be used, and a concurrency error will be reported
           //it.remove();
      }
       System.out.println(conllection.size());
​
       //judge
       System.out.println(conllection.contains("apple"));
       System.out.println(conllection.isEmpty());
  }
}
​
/*
Output results:
     Number of elements 3
     [apple, orange, banana]
     [orange, banana]
     orange
     banana
     orange
     banana
     2
     false
     false
*/

2. Use iterators to traverse the collection

Iterator has three methods for traversing collections

  1. hasNext(): determines whether there is a next element

  2. next(): get the next element

  3. remove(): deletes the current element

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
​
public class Demo02 {
   public static void main(String[] args) {
       //Create a new Collection object
       Collection collection=new ArrayList();
       Student stu1=new Student("tom",21);
       Student stu2=new Student("jerry",17);
       Student stu3=new Student("young",20);
       //1 add student data
       collection.add(stu1);
       collection.add(stu2);
       collection.add(stu3);
       collection.add(stu3);
       System.out.println(collection.toString());
       //2 delete
       collection.remove(stu2);
       System.out.println(collection.toString());
       //3 traversal
       //1 enhanced for
       for(Object obj:collection){
           Student s=(Student)obj;
           System.out.println(s.toString());
      }
       //2 iterator
       Iterator it=collection.iterator();
       while(it.hasNext()){
           Student s2=(Student)it.next();
           System.out.println(s2.toString());
      }
  }
}
​
/*
Output results:
     [Student[name=tom,age=21], Student[name=jerry,age=17], Student[name=young,age=20], Student[name=young,age=20]]
     [Student[name=tom,age=21], Student[name=young,age=20], Student[name=young,age=20]]
     Student[name=tom,age=21]
     Student[name=young,age=20]
     Student[name=young,age=20]
     Student[name=tom,age=21]
     Student[name=young,age=20]
     Student[name=young,age=20]
*/

List interface and implementation class

  • Features: orderly, subscript, elements can be repeated.

  • method

    • void add(int index,Object o): inserts object o at the index position

    • boolean addAll(int index,Collection c): add all elements in a collection to the index position in the collection

    • Object get(int index): returns the element at the specified position in the collection

    • List subList(int fromIndex,int tIndex): returns the elements between fromIndex and toIndex.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
​
public class Demo03 {
   //Use of List self interface
   public static void main(String[] args) {
       List list=new ArrayList<>();
       //1. Add collection elements
       list.add("apple");
       list.add("huawei");
       list.add("oppo");
       list.add("oppo");
       list.add("oppo");
       System.out.println(list.size());
       System.out.println(list.toString());
       //2. Delete
       list.remove("oppo");
       list.remove(1);
       System.out.println(list.toString());
       //3. Key points
       //3.1 for traversal
       for(int i=0;i<list.size();i++){
           System.out.println(list.get(i));
      }
       //3.2 enhanced for
       for(Object obj:list){
           System.out.println(obj);
      }
       //3.3 iterators
       Iterator it=list.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
       //3.4 using list iterators
       ListIterator lit=list.listIterator();
       while(lit.hasNext()){
           //From front to back
           System.out.println(lit.nextIndex());
           System.out.println(lit.next());
      }
       //Traverse from back to front
       while(lit.hasPrevious()){
           System.out.println(lit.previousIndex());
           System.out.println(lit.previous());
      }
​
       //4 judgment
       System.out.println(list.contains("oppo"));
       System.out.println(list.isEmpty());
​
       //5 get location
       System.out.println(list.indexOf("apple"));
  }
}
​
/*
Output results:
     5
     [apple, huawei, oppo, oppo, oppo]
     [apple, oppo, oppo]
     apple
     oppo
     oppo
     apple
     oppo
     oppo
     apple
     oppo
     oppo
     0
     apple
     1
     oppo
     2
     oppo
     2
     oppo
     1
     oppo
     0
     apple
     true
     false
     0
*/

1. List iterator

  1. The list iterator can traverse forward and backward in any direction.

  2. You can also add, delete, and modify elements.

import java.util.ArrayList;
import java.util.List;
​
public class Demo04 {
   public static void main(String[] args) {
       List list=new ArrayList();
       //1. The collection cannot save numeric types. When adding numeric types, an operation will be performed automatically to automatically pack
       list.add(10);
       list.add(20);
       list.add(30);
       list.add(40);
       list.add(50);
       System.out.println(list.toString());
       //2. Delete
       list.remove(new Integer(20));
       System.out.println(list.toString());
​
       //3 supplementary method sublist, including head and tail
       List sublist=list.subList(0,2);
       System.out.println(sublist.toString());
​
​
  }
}
​
/*
Output results:
     [10, 20, 30, 40, 50]
     [10, 30, 40, 50]
     [10, 30]
*/

2.List interface implementation class

ArrayList

  • ArrayList [key]

    • Array structure implementation, fast query, slow addition and deletion;

    • JDK1.2 version has fast operation efficiency and unsafe thread;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
​
public class Demo05 {
   public static void main(String[] args) {
       ArrayList al=new ArrayList();
       //1. Add elements
       Student s1=new Student("a",10);
       Student s2=new Student("b",20);
       Student s3=new Student("c",30);
       al.add(s1);
       al.add(s2);
       al.add(s3);
       System.out.println(al.size());
       System.out.println(al.toString());
​
       //2. Delete element
       al.remove(new Student("a",10));//Override the equals method
       System.out.println(al.size());
​
       //3. Traverse elements [ key ]
       //3.1 iterators
       Iterator it=al.iterator();
       while(it.hasNext()){
           Student s=(Student)it.next();
           System.out.println(s.toString());
      }
       //3.2 list iterators
       ListIterator lit=al.listIterator();
       while(lit.hasNext()){
           Student s=(Student)lit.next();
           System.out.println(s.toString());
      }
​
       while (lit.hasPrevious()){
           Student s=(Student)lit.previous();
          System.out.println(s.toString());
        }
​
       //4. Judgment
       System.out.println(al.contains(new Student("b",20)));
       System.out.println(al.isEmpty());
​
       //5. Find
       System.out.println(al.indexOf(new Student("b",20)));
  }
}
​
/*
Output results:
     3
     [Student[name=a,age=10], Student[name=b,age=20], Student[name=c,age=30]]
     2
     Student[name=b,age=20]
     Student[name=c,age=30]
     Student[name=b,age=20]
     Student[name=c,age=30]
     Student[name=c,age=30]
     Student[name=b,age=20]
     true
     false
     0
     -1
*/

Vector

  • Vector

    • Array structure implementation, fast query, slow addition and deletion;

    • JDK1.0 version, slow running efficiency and thread safety

import java.util.Enumeration;
import java.util.Vector;
​
public class Demo06 {
   public static void main(String[] args) {
       //Create collection
       Vector vec = new Vector();
       vec.add("strawberry");
       vec.add("Apple");
       vec.add("Banana");
       System.out.println(vec.size());
       //ergodic
       //enumerator 
       Enumeration en=vec.elements();
       while(en.hasMoreElements()){
           Object obj=en.nextElement();
           System.out.println(obj);
      }
       //judge
       System.out.println(vec.contains("watermelon"));
       //Other methods
  }
}
​
/*
Output results:
     3
     strawberry
     Apple
     Banana
     false
*/

LinkedList

  • LinkedList

    • Linked list structure implementation, fast addition and deletion, slow query.

import java.util.Iterator;
import java.util.LinkedList;
​
public class Demo07 {
   public static void main(String[] args) {
       //create object
       LinkedList ll=new LinkedList();
       Student s1=new Student("a",10);
       Student s2=new Student("b",20);
       Student s3=new Student("c",30);
       Student s4=new Student("c",30);
       //add to
       ll.add(s1);
       ll.add(s2);
       ll.add(s3);
       System.out.println(ll.size());
       System.out.println(ll.toString());
       //delete
       ll.remove(new Student("a",10));
       System.out.println(ll.size());
       //ergodic
       //for
       for(int i=0;i<ll.size();i++){
           System.out.println(ll.get(i));
      }
       //Enhanced for
       for(Object o:ll){
           Student stu = (Student) o;
           System.out.println(stu);
      }
       //iterator 
       Iterator it=ll.iterator();
       while(it.hasNext()){
           Student s= (Student) it.next();
           System.out.println(s.toString());
      }
       //judge
       //obtain
       System.out.println(ll.indexOf(s2));
  }
}
​
/*
Output results:
     3
     [Student[name=a,age=10], Student[name=b,age=20], Student[name=c,age=30]]
     2
     Student[name=b,age=20]
     Student[name=c,age=30]
     Student[name=b,age=20]
     Student[name=c,age=30]
     Student[name=b,age=20]
     Student[name=c,age=30]
     0
*/

Generics and utility classes

  • Java generics is a new feature introduced in JDK 1.5. Its essence is parameterized types, which are passed as parameters.

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

  • Syntax: < T,... > t is called a type placeholder, and a table is a reference type.

  • Benefits:

    1. Improve code reusability

    2. Prevent type conversion exceptions and improve code security

⚠️ be careful

  1. Generic types can only be reference types.

  2. Objects of different generic types cannot copy each other.

1. Generic class

//Create a generic class
//Generic class
public class MyGeneric<T> {
   //Use generic T
   //1.0 creating variables
   T t;
   //2.0 as a parameter of the method
   public void show(T t){
       System.out.println(t);
  }
   //Generic as return value of method
   public T getT(){
       return t;
  }
}
public class Demo08 {
   public static void main(String[] args) {
       //Creating objects using generic classes
       MyGeneric<String> mg=new MyGeneric<>();
       mg.t="hello";
       mg.show("Hello");
       String s=mg.getT();
       System.out.println(s.toString());
​
       MyGeneric<Integer> mg2=new MyGeneric<>();
       mg2.t=20;
       mg2.show(30);
  }
}
​
/*
Output results:
     Hello
     hello
     30
*/

2. Generic interface

1. Create a generic interface first

//generic interface 
public interface MyInterface<T> {
    String name="Zhang San";

    public T server(T t);
}

2. Create an interface implementation class

The generic type can be determined in the implementation class

public class MyInterfaceImp implements MyInterface<String> {
​
   @Override
   public String server(String s) {
       System.out.println(s);
       return s;
  }
}

You can also continue to create a generic class without being sure

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

In the final implementation class, create objects with two types respectively, and find their differences

public class Test {
    public static void main(String[] args) {
        MyInterfaceImp imp1=new MyInterfaceImp();
        imp1.server("xxxxxx");

        MyInterfaceImp2<String> imp2= new MyInterfaceImp2<>();
        imp2.server("aaaaaa");
    }

}

/*
Output results:
      xxxxxx
      aaaaaa
*/

3. Generic methods

public class MyGenericMethod {
   //generic method 
   public <T> T show(T t){
       System.out.println("generic method "+t);
       return t;
  }
}
public class Test {
   public static void main(String[] args) {
       MyGenericMethod mm=new MyGenericMethod();
       mm.show("Go China");
       mm.show(200);
       mm.show(3.14);
  }
​
}
​
/*
Output results:
     Generic method China refueling
     Generic method 200
     Generic method 3.14
*/

4. Generic collection

  • Concept: parameterized type and type safe collection, and the types of collection elements must be consistent.

  • characteristic:

    • You can check at compile time, not the exception thrown at run time.

    • Type conversion (unpacking) is not necessary when accessing.

    • References between different generics cannot be converted to each other, and there is no polymorphism in generics.

public class Demo09 {
   public static void main(String[] args) {
       ArrayList<String> al=new ArrayList<>();
       al.add("xxx");
       al.add("yyy");
      // al.add(10);
       //al.add(20);
​
       for(String o:al){
           System.out.println(o);
      }
​
       ArrayList<Student> al2=new ArrayList<>();
       Student s1=new Student("a",1);
       Student s2=new Student("b",2);
       Student s3=new Student("c",3);
       al2.add(new Student("c",4));
       al2.add(s1);
       al2.add(s2);
       al2.add(s3);
​
       Iterator<Student> it= al2.iterator();
       while(it.hasNext()){
           Student s=it.next();
           System.out.println(s.toString());
      }
  }
}
​
/*
Output results:
     xxx
     yyy
     Student[name=c,age=4]
     Student[name=a,age=1]
     Student[name=b,age=2]
     Student[name=c,age=3]
*/

Set interface and implementation class

  • Features: disorder, no subscript, and elements cannot be repeated.

  • Methods: all inherit from the Collection interface

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
​
public class Demo01 {
   public static void main(String[] args) {
       Set<String> set=new HashSet<>();
       //1. Add data
       set.add("Apple");
       set.add("Huawei");
       set.add("millet");
       System.out.println("Number of data"+set.size());
       System.out.println(set.toString());
       //2. Delete
       //set.remove("Xiaomi");
       //3. Key points
       //1. Enhance for
       for(String str:set){
           System.out.println(str);
      }
​
       //2. Iterator traversal
       Iterator<String> it=set.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
​
       //4. Judgment
       System.out.println(set.contains("Huawei"));
       System.out.println(set.isEmpty());
  }
}
​
/*
Output results:
     Number of data 3
     [Apple, Huawei, Xiaomi]
     Apple
     Huawei
     millet
     Apple
     Huawei
     millet
     true
     false
*/

1.Hashset

  • Implement element non repetition based on HashCode

  • When the hash codes of the stored elements are the same, equals will be called for confirmation. If it is true, the latter will be rejected.

import java.util.HashSet;
import java.util.Iterator;
​
public class Demo02 {
   public static void main(String[] args) {
       //Demonstrates the use of hashset sets
       //Hash table (array + linked list)
       HashSet<String> hs=new HashSet<>();
       hs.add("Lau Andy");
       hs.add("Chao Wei Liang");
       hs.add("Zhi Ying Lin");
       hs.add("Zhou Runfa");
       //hs.add("Chow Yun Fat");
       System.out.println(hs.size());
       System.out.println(hs.toString());
​
       hs.remove("Lau Andy");
       System.out.println(hs.toString());
​
       for(String str:hs){
           System.out.println(str);
      }
​
       Iterator<String> it=hs.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
​
       System.out.println(hs.contains("Guo Fucheng"));
       System.out.println(hs.isEmpty());
  }
}
​
/*
Output results:
     4
     [Liang Chaowei, Lin Zhiying, Zhou Runfa, Andy Lau]
     [Liang Chaowei, Lin Zhiying, Zhou Runfa]
     Chao Wei Liang
     Zhi Ying Lin
     Zhou Runfa
     Chao Wei Liang
     Zhi Ying Lin
     Zhou Runfa
     false
     false
*/
import java.util.HashSet;
import java.util.Iterator;
​
public class Demo03 {
   public static void main(String[] args) {
       HashSet<Person> hs=new HashSet<>();
       Person p1=new Person("Lau Andy",20);
       Person p2=new Person("Li Muyang",30);
       Person p3=new Person("Zhou Runfa",40);
       Person p4=new Person("Wang Qian",50);
​
       hs.add(p1);
       hs.add(p2);
       hs.add(p3);
       hs.add(p4);
​
       System.out.println(hs.size());
       System.out.println(hs.toString());
​
       hs.add(new Person("Wang Qian",50));//Override hashcode and equals methods
​
       hs.remove(p1);
       System.out.println(hs.toString());
​
       for(Person per:hs){
           System.out.println(per);
      }
​
       Iterator<Person> it=hs.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
​
       System.out.println(hs.contains(p1));
  }
}
​
/*
     4
     [Student[name=Zhou Runfa, age=40], Student[name = Andy Lau, age=20], Student[name = Wang Qian, age=50], Student[name = Li Muyang, age=30]]
     [Student[name=Zhou Runfa, age=40], Student[name = Wang Qian, age=50], Student[name = Li Muyang, age=30]]
     Student[name=Zhou Runfa, age=40]
     Student[name=Wang Qian, age=50]
     Student[name=Li Muyang, age=30]
     Student[name=Zhou Runfa, age=40]
     Student[name=Wang Qian, age=50]
     Student[name=Li Muyang, age=30]
     false
*/

⚠️ To avoid adding duplicate elements, the equals method and hashcode method need to be overridden in the Person class

 
  @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);
  }

2.TreeSet

  • Based on the arrangement order, the elements are not repeated.

  • The SortedSet interface is implemented to automatically sort the set elements.

  • The type of the element object must implement the Comparable interface to specify the collation.

  • Determine whether it is a duplicate element through the CompareTo method.

import java.util.Iterator;
import java.util.TreeSet;
​
public class Demo04 {
   public static void main(String[] args) {
       //Use of treeset
       TreeSet<String> ts = new TreeSet<>();
       //Add element
       ts.add("good");
       ts.add("bonjour");
       ts.add("hello");
       ts.add("hi");
       System.out.println("Number of elements" + ts.size());
       System.out.println(ts.toString());
​
       //Add duplicate elements
       ts.add("hi");
       System.out.println(ts.size());//fail
​
       //delete
       ts.remove("hi");
       System.out.println(ts.toString());
​
       //ergodic
       for (String str : ts) {
           System.out.println(str);
      }
​
       Iterator<String> it=ts.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
  }
}
​
/*
Output results:
     Number of elements 4
     [bonjour, good, hello, hi]
     4
     [bonjour, good, hello]
     bonjour
     good
     hello
     bonjour
     good
     hello
*/
import java.util.Iterator;
import java.util.TreeSet;
​
public class Demo05 {
   public static void main(String[] args) {
       TreeSet<Person> ts=new TreeSet<>();
       Person p1=new Person("Li Muyang",21);
       Person p2=new Person("Wang Qian",23);
       Person p3=new Person("Li xinwen",19);
       Person p4=new Person("eldest brother",20);
       Person p5=new Person("eldest brother",20);
​
       //add to
       ts.add(p1);
       ts.add(p2);
       ts.add(p3);
       ts.add(p4);
       System.out.println("Number of people"+ts.size());
       System.out.println(ts.toString());
​
       ts.remove(new Person("eldest brother",20));
       System.out.println(ts.size());
​
       //ergodic
       for(Person per:ts){
           System.out.println(per);
      }
​
       Iterator<Person> it=ts.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
  }
}
​
/*
Output results:
     Number 4
     [Student[name=Big brother, age=20], Student[name = Li Muyang, age=21], Student[name = Li Xinwen, age=19], Student[name = Wang Qian, age=23]]
     3
     Student[name=Li Muyang, age=21]
     Student[name=Li Xinwen, age=19]
     Student[name=Wang Qian, age=23]
     Student[name=Li Muyang, age=21]
     Student[name=Li Xinwen, age=19]
     Student[name=Wang Qian, age=23]
*/

⚠️: The Comparable interface needs to be implemented

Therefore, you must implement the interface and override the CompareTo method in the Person class

@Override
   public int compareTo(Object o) {
       Person p=(Person) o;
       int n1=this.getName().compareTo(p.getName());
       int n2=this.age-p.getAge();
​
       return n1==0?n2:n1;
  }

3.Comparator interface

  • Comparable: comparable

  • Comparator: implement custom comparison (comparator)

import java.util.Comparator;
import java.util.TreeSet;
​
public class Demo06 {
   public static void main(String[] args) {
       TreeSet<Person> ts=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("Li Muyang",21);
       Person p2=new Person("Wang Qian",23);
       Person p3=new Person("Li xinwen",19);
       Person p4=new Person("eldest brother",20);
       Person p5=new Person("eldest brother",20);
​
       ts.add(p1);
       ts.add(p2);
       ts.add(p3);
       ts.add(p4);
       ts.add(p5);
       System.out.println(ts.size());
       System.out.println(ts.toString());
  }
}
​
/*
Output results:
     4
     [Student[name=Li Xinwen, age=19], Student[name = big brother, age=20], Student[name = Li Muyang, age=21], Student[name = Wang Qian, age=23]]
*/

Case (customized by length comparison)

import java.util.Comparator;
import java.util.TreeSet;
​
public class Demo07 {
   public static void main(String[] args) {
       TreeSet<String> ts=new TreeSet<>(new Comparator<String>() {
           @Override
           public int compare(String o1, String o2) {
               int n1=o1.length()-o2.length();
               int n2=o2.compareTo(o2);
               return n1==0?n2:n1;
          }
      });
​
       ts.add("helloworld");
       ts.add("iphone");
       ts.add("beijing");
       ts.add("tomcat");
       ts.add("xian");
       ts.add("changsha");
       ts.add("wuxi");
​
       for(String str:ts){
           System.out.println(str);
      }
​
  }
}
​
/*
Output results:
     xian
     iphone
     beijing
     changsha
     helloworld
*/

Map interface and implementation class

characteristic:

  • Used to store any key value pair

  • Key: unordered, no subscript, no repetition (unique)

  • Value: unordered, no subscript, duplicate allowed

1.Map parent interface

  • Features: store a pair of data (key value), unordered, no subscript, the key can not be repeated, and the value can be repeated.

  • method:

    • V put(K key,V value) / / store the object in the collection and associate the key value. If the key is repeated, the original value will be overwritten.

    • Object get(Object key) / / obtain the corresponding value according to the key.

    • Set < k > / / returns all key s.

    • Collection < V > values() / / returns a collection containing all values.

    • Set < map. Entry < k.v > > / / set with matching key value.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
​
public class Demo01 {
   public static void main(String[] args) {
       Map<String,String> map=new HashMap<>();
       //Add element
       map.put("cn","China");
       map.put("uk","britain");
       map.put("usa","U.S.A");
       System.out.println(map.size());
       System.out.println(map.toString());
       //Delete element
       map.remove("usa");
       System.out.println(map.size());
       //Traversal element
       //1:keySet()
       Set<String> ks=map.keySet();
       for(String str:ks){
           System.out.println(str+"="+map.get(str));
      }
​
       //2. Use entryset()
       Set<Map.Entry<String,String>> mn=map.entrySet();
       for(Map.Entry<String,String> entry:mn){
           System.out.println(entry.getKey()+entry.getValue());
      }
  }
}
​
/*
Output results:
     3
     {usa=USA, uk = uk, cn = China}
     2
     uk=britain
     cn=China
     uk britain
     cn China
*/

2.HashMap

  • In JDK1.2, the thread is unsafe and the operation efficiency is fast. null is allowed as key or value.

  • Hashtable:JDK1.0, thread safe and slow running efficiency; null is not allowed as key or value

package jihe3;
​
import java.util.HashMap;
import java.util.Map;
​
HashMap Use of; Storage structure: (array)+Linked list+Red black tree)
public class Demo02 {
   public static void main(String[] args) {
       //Create collection
       HashMap<Student,String> student=new HashMap<>();
       //Add element
       Student s1=new Student(100,"Sun WuKong");
       Student s2=new Student(1200,"Sha Wujing");
       Student s3=new Student(1300,"Zhu Bajie");
       student.put(s1,"Beijing");
       student.put(s2,"Shanghai");
       student.put(s3,"Nanjing");
       student.put(s3,"Guangzhou");
       student.put(new Student(1300,"Zhu Bajie"),"Guangzhou");//Override hashcode and equals methods
       System.out.println("Number of elements"+student.size());
       System.out.println(student.toString());
       //delete
       student.remove(s1);
       System.out.println("After deletion"+student.size());
       //3.1 enhanced for traversal
       for(Student stu:student.keySet()){
           System.out.println(stu.toString()+"========"+student.get(stu));
      }
       //3.2entrySet()
       for(Map.Entry<Student,String> entry:student.entrySet()){
           System.out.println(entry.getKey()+"======="+entry.getValue());
      }
       //judge
       System.out.println(student.containsKey(s1));
       System.out.println(student.containsValue("Nanjing"));
  }
}
​
/*
Output results:
     Number of elements 3
     {Student{age=100, name='Monkey King '} = Beijing, Student{age=1300, name =' zhubajie '} = Guangzhou, Student{age=1200, name =' shawujing '} = Shanghai}
     After deletion 2
     Student{age=1300, name='Zhu Bajie '} ========== Guangzhou
     Student{age=1200, name='Shawujing '} ========== Shanghai
     Student{age=1300, name='Zhu Bajie '} ========= Guangzhou
     Student{age=1200, name='Shawujing '} ========= Shanghai
     false
     false
*/

3.TreeMap

  • SortedMap interface (a sub interface of Map) is implemented to automatically sort key s.

package jihe3;
​
import OOP.Demo17.Stu;
​
import java.util.Map;
import java.util.TreeMap;
​
public class Demo03 {
   public static void main(String[] args) {
       TreeMap<Student,String> tm=new TreeMap<>();
​
       Student s1=new Student(100,"Sun WuKong");
       Student s2=new Student(1200,"Sha Wujing");
       Student s3=new Student(1300,"Zhu Bajie");
​
       tm.put(s1,"Beijing");
       tm.put(s2,"Shanghai");
       tm.put(s3,"Shenzhen");
       tm.put(new Student(1300,"Zhu Bajie"),"Shenzhen");
​
       System.out.println(tm.size());
       System.out.println(tm.toString());
​
       for(Student key:tm.keySet()){
           System.out.println(key+"========"+tm.get(key));
      }
​
       for (Map.Entry<Student,String> entry:tm.entrySet()){
           System.out.println(entry.getKey()+"======="+entry.getValue());
      }
  }
}
​
/*
Output results:
3
     {Student{age=100, name='Monkey King '} = Beijing, Student{age=1200, name =' shawujing '} = Shanghai, Student{age=1300, name =' zhubajie '} = Shenzhen}
     Student{age=100, name='Monkey King '} =========== Beijing
     Student{age=1200, name='Shawujing '} ========== Shanghai
     Student{age=1300, name='Zhu Bajie '} ========== Shenzhen
     Student{age=100, name='Monkey King '} ========= Beijing
     Student{age=1200, name='Shawujing '} ========= Shanghai
     Student{age=1300, name='Zhu Bajie '} ========= Shenzhen
*/

4.Collections tool class

Concept: collection tool class, which defines common collection methods other than access

  • method:

    • Public static void reverse (list <? > list) / / reverse the order of elements in the collection

    • Public static void shuffle (list <? > list) / / randomly reset the order of elements

    • public static void sort()List<?> List / / sort in ascending order (elements must implement the Comparable interface)

package jihe3;
​
import java.util.*;
​
public class Demo04 {
   public static void main(String[] args) {
       List<Integer> list=new ArrayList<>();
       list.add(20);
       list.add(30);
       list.add(40);
       list.add(50);
       list.add(60);
       //Sort sort
       System.out.println("Before sorting"+list.toString());
       Collections.sort(list);
       System.out.println("After sorting"+list.toString());
​
       //binarySearch query
       int i=Collections.binarySearch(list,50);
       System.out.println(i);
​
       //Copy copy
       List<Integer> list2=new ArrayList<>();
       for (int j=0;j<list.size();j++){
           list2.add(0);
      }
       Collections.copy(list2,list);
       System.out.println(list2.toString());
​
       //Reverse reverse
       Collections.reverse(list);
       System.out.println("After reversal"+list.toString());
​
       //shuffle
       Collections.shuffle(list);
       System.out.println("After disruption"+list.toString());
​
       //Add, list is converted to array
       Integer[] arr=list.toArray(new Integer[0]);
       System.out.println(arr.length);
       System.out.println(Arrays.toString(arr));
​
       //Convert array to collection
       String[] name={"Zhang San","Li Si","Wang Wu"};
       List<String> list3=Arrays.asList(name);//Collection is a restricted collection and cannot be added or deleted
       //When a basic type is converted to a collection, it is written as a wrapper class
       System.out.println(list3.toString());
  }
}
​
/*
Output results:
     Top [20, 30, 40, 50, 60]
     After sorting [20, 30, 40, 50, 60]
     3
     [20, 30, 40, 50, 60]
     After reversal [60, 50, 40, 30, 20]
     After disruption [30, 40, 20, 50, 60]
     5
     [30, 40, 20, 50, 60]
     [Zhang San, Li Si, Wang Wu]
*/

Keywords: Java Back-end Typora

Added by steve m on Sat, 04 Dec 2021 06:30:31 +0200