当前位置:网站首页>aggregate

aggregate

2020-11-10 17:46:24 Handsome cochlea

aggregate

What is a collection

  • Concept

    Object's container , It implements the common operations on objects

  • The difference with arrays

    1. Array length is fixed , The set length is not fixed

    2. Arrays can store basic types and reference types , A collection can only store reference types

 

Collection system

Collection The parent interface

characteristic : Represents a set of objects of any type , disorder 、 No subscript 、 Can't repeat .

Create set Collection collection = new ArrayList();

  • Common methods

  1. Additive elements collection.add();

  2. Remove elements

    collection.remove();

    collection.clear();

  3. Traversing elements ( a key )

    1. Use enhancements for( Because there is no subscript )

      for(Object object : collection){ }

    2. Using Iterators

       

      //hasNext();  There's no next element 
      //next(); Get next element
      //remove(); Delete current element
      Iterator it = collection.iterator();
      while(it.hasNext()){
      String object = (String)it.next(); // Strong go
      // have access to it.remove(); To remove the element
      // collection.remove(); Out-of-service collection Other methods Concurrent modification exception reported
      }
  4. Judge collection.contains(); collection.isEmpty();

  • Code reference

    package com.pc.zjs;

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;

    /**
    * Collection Use of interfaces
    *(1) Additive elements
    *(2) Remove elements
    *(3) Traversing elements
    *(4) Judge
    */
    public class Demo01 {
       public static void main(String[] args) {
           // Create set
           Collection collection=new ArrayList();
           //(1) Additive elements
           collection.add(" Apple ");
           collection.add(" watermelon ");
           collection.add(" durian ");
           System.out.println(" Element number "+collection.size());
           System.out.println(collection);
           // Remove elements
           //collection.remove(" durian ");
           //collection.clear(); Delete all
           //System.out.println(" After deleting "+collection.size());
           //(3) Traversing elements
           //3.1 enhance for
           System.out.println("------ Use enhancements for-------");
           for(Object object:collection){
               System.out.println(object);
          }
           //3.2 Using Iterators
           /*
           hasNext(); There's no next element
           next(); Get next element
           remove(); Delete current element
            */
           System.out.println("------ Using Iterators --------");
           Iterator it=collection.iterator();
           while (it.hasNext()){
               String s = (String)it.next();
               System.out.println(s);
               //collection.remove(s); Here the iterator is using collection Don't allow to collection To operate
               it.remove();
          }
           System.out.println(" Element number "+collection.size());
           /*
           (4) Judge
            */
           System.out.println(collection.contains(" watermelon "));
           System.out.println(collection.isEmpty());
      }
    }

     

package com.pc.zjs;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
* Collection Use : Save student information
*/
public class Demo02 {
   public static void main(String[] args) {
       // newly build Collection object
        Collection collection = new ArrayList<>();
        Student s1=new Student(" Zhang San ",20);
        Student s2=new Student(" zhang wuji ",18);
        Student s3=new Student(" The king 2 ",22);
        //1. Add data
       collection.add(s1);
       collection.add(s2);
       collection.add(s3);
       System.out.println(" Element number "+collection.size());
       System.out.println(collection.toString());
       //2. Delete
       //collection.remove(s1);
       //collection.clear();
       //System.out.println(" After deleting "+collection.size());
       //3. Traverse
       /*
       3.1 enhance for
        */
       System.out.println("---- Use enhancements for----");
       for(Object object:collection){
           Student s=(Student)object;
           System.out.println(s.toString());
      }
       //3.2 iterator
       System.out.println("--- Using Iterators ---");
       Iterator it = collection.iterator();
       while (it.hasNext()){
           Student s = (Student)it.next();
           System.out.println(s.toString());
      }
       //4. Judge
       System.out.println(collection.contains(s1));
       System.out.println(collection.isEmpty());
  }
}
package com.pc.zjs;

public class Student {
   private String name;
   private int age;

   public Student() {
  }

   public Student(String name, int age) {
       //super();
       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 A subinterface

characteristic : Orderly 、 With subscript 、 Element repeatable

Create a collection object List list = new ArrayList<>( );

  • Common methods

    1. Additive elements list.add( ); The basic types will be automatically boxed

    2. Remove elements You can use the index list.remove(0)

      When deleting a number conflicts with an index Turn the numbers around

      list.remove((Object) 10) or list.remove(new Integer(10))

    3. Traverse

      1. Use for Traverse

         

        for(int i = 0; i < list.size(); i++){
        sout(list.get(i));
        }
      2. Use enhancements for

        for(Object list: collection){ }

      3. Using Iterators

         

        Iterator it = collection.iterator();
        while(it.hasNext()){
        String object = (String)it.next(); // Strong go
        // have access to it.remove(); To remove the element
        // collection.remove(); Out-of-service collection Other methods Concurrent modification exception reported
        }
      4. Using list iterators ( Notice the difference from iterators )

         

        ListIterator li = list.listIterator();
        while(li.hasNext()){
        System.out.println(li.nextIndex() + ":" + li.next()); // Traversing from front to back
        }

        while(li.hasPrevious()){
        System.out.println(li.previousIndex() + ":" + li.previous()); // Go back and forth
        }
    4. obtain list.indexOf( );

    5. Return subsets sublist(x, y); Left closed right away

      List subList = list.subList(1, 3); Returns the index 1、2

       

List Implementation class

  • ArrayList 【 a key 】

    • Array structure implementation , It has to be continuous space , Quick query 、 Add or delete slowly

    • jdk1.2 edition , Operating efficiency block 、 Thread unsafe

  • Vector

    • Array structure implementation , Quick query 、 Add or delete slowly

    • jdk1.0 edition , function

  • LinkedList

    • Implementation of bidirectional linked list structure , There's no need for continuous space , Additions and deletions quickly , Slow query

ArrayList

Create set ArrayList arrayList = new ArrayList<>();

  1. Additive elements arrayList.add();

  2. Remove elements arrayList.remove(new Student("name", 10));

It's rewritten here equals(this == obj) Method

public boolean equals(Object obj){
 //1 Judge whether it is the same object
 if(this == obj){
   return true;
}
 //2 Determine whether it is null
 if(obj == null){
   return false;
}
 //3 Judge whether it is Student type
 if(obj instanceof Student){
   Student == (Student)obj;
   //4 Comparison properties
   if(this.name.equals(s.getName()) && this.age == s.getAge()){
     return true;
  }
}
 //5 Not satisfied return false
 return false;
}
  1. Traversing elements 【 a key 】

    1. Using Iterators

       

      Iterator it = arrayList.iterator();
      while(it.hasNext()){
      Student s = (Student)it.next(); // Strong go
      }
    2. List iterator

       

      ListIterator li = arrayList.listIterator();
      while(li.hasNext()){
      Student s = (Student)li.next(); // Traversing from front to back
      }

      while(li.hasPrevious()){
      Student s = (Student)li.previous();// Go back and forth
      }
  2. Judge

    arrayList.contains(); and arrayList.isEmpty();

  3. lookup

    arrayList.indexof();

     

Reference code

package com.pc.zjs;

import java.util.ArrayList;
import java.util.List;

public class Demo04 {
   public static void main(String[] args) {
       // Create set
       List list=new ArrayList();
       //1. Add digital data ( Automatic boxing )
       list.add(20);
       list.add(30);
       list.add(40);
       list.add(50);
       list.add(60);
       System.out.println(" Element number "+list.size());
       System.out.println(list.toString());

       //2 Delete operation
       //list.remove(0);
       list.remove((Object)20);
       //list.remove(new Integer(20));
       System.out.println(" Remove elements "+list.size());
       System.out.println(list.toString());
       //3 Supplementary methods sublist, Return subsets and , With head and no tail
       List sublist=list.subList(1, 3);
       System.out.println(sublist.toString());
  }
}


package com.pc.zjs;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

/**
* ArrayList Use
*/
public class Demo05 {
   public static void main(String[] args) {
       ArrayList arrayList=new ArrayList<>();
       //1. Additive elements
       Student s1=new Student(" Lau Andy ",20);
       Student s2=new Student(" Aaron Kwok ",22);
       Student s3=new Student(" Tony Leung ",18);
       arrayList.add(s1);
       arrayList.add(s2);
       arrayList.add(s3);
       System.out.println(" Element number "+arrayList.size());
       System.out.println(arrayList.toString());
       //2. Remove elements
       //arrayList.remove(s1);
       arrayList.remove(new Student(" Lau Andy ",20));
       System.out.println(" After deleting "+arrayList.size());

       //3. Traversing elements 【 a key 】
       //3.1 Using Iterators
       System.out.println("--- Using Iterators ---");
       Iterator it = arrayList.iterator();
       while (it.hasNext()){
           Student s = (Student)it.next();
           System.out.println(s.toString());
      }
       //3.2 Using list iterators
       System.out.println("--- Using list iterators ---");
       ListIterator lit = arrayList.listIterator();
       while (lit.hasNext()){
           Student s = (Student)lit.next();
           System.out.println(s.toString());
      }
       System.out.println("--- Use the list iterator to reverse order ---");
       while (lit.hasPrevious()){
           Student s=(Student)lit.previous();
           System.out.println(s.toString());
      }
       //4. Judge
       System.out.println(arrayList.contains(new Student(" Tony Leung ",18)));
       System.out.println(arrayList.isEmpty());
       //5. lookup
       System.out.println(arrayList.indexOf(new Student(" Tony Leung ",18)));
  }
}
package com.pc.zjs;

public class Student {
   private String name;
   private int age;

   public Student() {
  }

   public Student(String name, int age) {
       //super();
       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 +
               '}';
  }

   @Override
   public boolean equals(Object obj) {
       //1. Judge whether it is the same object
       if(this==obj){
           return true;
      }
       //2. Determine whether it is null
       if(obj==null){
           return false;
      }
       //3. Judge whether it is Student type
       if(obj instanceof Student){
           Student s=(Student)obj;
           //4. Comparison properties
           if(this.name.equals(s.getName())&&this.age==s.getAge()){
               return true;
          }
      }
       //5. Not satisfied return false
       return false;
  }

}

ArrayList Source code analysis

DEFAULT_CAPACITY = 10; // The default volume 
// Be careful : If you don't add any elements to the collection , Capacity 0, After adding one , Capacity of 10
// Each expansion is original 1.5 times
elementData An array of elements
size The actual number of elements

Vector

Create set Vector vector = new Vector<>();

increase 、 Delete 、 The judgment is the same as above

In traversal, enumerator traverses

Enumeration en = vector.elements();
while(en.hasMoreElements()){
 String o = (String)en.nextElement();
 sout(o);
}

package com.pc.zjs01;

import java.util.Enumeration;
import java.util.Vector;

/**
* demonstration Vector Use
*/
public class Demo01 {
   public static void main(String[] args) {
       // Create set
       Vector vector=new Vector<>();
       //1. Additive elements
       vector.add(" strawberry ");
       vector.add(" Mango. ");
       vector.add(" watermelon ");
       System.out.println(" Element number "+vector.size());
       //2. Delete
//       vector.remove(0);
//       vector.remove(" watermelon ");
//       vector.clear();
       //3. Traverse
       // Using an enumerator
       Enumeration en=vector.elements();
       while (en.hasMoreElements()){
           String o=(String)en.nextElement();
           System.out.println(o);
      }
       // Judge
       System.out.println(vector.contains(" watermelon "));
       System.out.println(vector.isEmpty());
       //vector Other methods
       //firstElement,lastElement,elementAt();

  }
}

LinkedList

Create a linked list collection LinkedList li = new LinkedList<>();

Common methods and List Agreement

package com.pc.zjs01;

import com.pc.zjs.Student;

import java.util.Iterator;
import java.util.LinkedList;

/**
* LinkedList Use
*
*/
public class Demo02 {
   public static void main(String[] args) {
       // Create set
       LinkedList linkedList=new LinkedList<>();
       //1. Additive elements
       Student s1=new Student(" Lau Andy ",20);
       Student s2=new Student(" Aaron Kwok ",22);
       Student s3=new Student(" Tony Leung ",18);
       linkedList.add(s1);
       linkedList.add(s2);
       linkedList.add(s3);
       System.out.println(" Element number "+linkedList.size());
       System.out.println(linkedList.toString());
       //2. Delete
//       linkedList.remove(new Student(" Lau Andy ",20));
//       System.out.println(" After deleting "+linkedList.size());
//       linkedList.clear();
       //3. Traverse
       //3.1for Traverse
       System.out.println("---for Traverse ---");
       for (int i = 0; i < linkedList.size(); i++) {
           System.out.println(linkedList.get(i));
      }
       //3.2 enhance for
       System.out.println("--- enhance for---");
       for(Object object:linkedList){
           Student s=(Student)object;
           System.out.println(s.toString());
      }
       //3.3 Using Iterators
       System.out.println("--- Using Iterators ---");
       Iterator it = linkedList.iterator();
       while (it.hasNext()){
           Student s= (Student) it.next();
           System.out.println(s.toString());
      }
       //3.4 Using list iterators
       System.out.println("--- Using list iterators ---");
       Iterator lit = linkedList.listIterator();
       while (lit.hasNext()){
           Student s= (Student) lit.next();
           System.out.println(s.toString());
      }
       //4 Judge
       System.out.println(linkedList.contains(s1));
       System.out.println(linkedList.isEmpty());
       //5 obtain
       System.out.println(linkedList.indexOf(s2));
  }
}

 

Generic

  • It's essentially a parametric type , Pass the type as an argument

  • Common forms are generic classes 、 Generic interface 、 Generic methods

  • grammar <T,...> T It's called a type placeholder , Represents a reference type , You can write multiple commas to separate them

  • benefits 1. Improve code reuse 2. Prevent type conversion exceptions , Improve code security

Generic classes

package com.pc.zjs01;

/**
* Generic classes
* T It's a type placeholder , Represents a reference type , If you write more than one, separate them with commas
*/
public class MyGeneric<T> {
   // Use generics T
   //1. Create variables
   T t;
   //2 Generics as parameters of methods
   public void show(T t){
       //T t1=new T(); Can't instantiate
       System.out.println(t);
  }
   //3. Generics as the return value of a method
   public T getT(){
       return t;
  }
}
package com.pc.zjs01;

public class TestGeneric {
   public static void main(String[] args) {
       // Using generic classes to create objects

       // Generics can only be reference types , Objects of different generic types cannot be assigned to each other
       MyGeneric<String> myGeneric=new MyGeneric<String>();
       myGeneric.t="hello";
       myGeneric.show(" Hello everyone , come on. ");
       String string=myGeneric.getT();
       MyGeneric<Integer> myGeneric2=new MyGeneric<Integer>();
       myGeneric2.t=100;
       myGeneric2.show(200);
       Integer integer=myGeneric2.getT();
  }
}

Generic interface

grammar : The interface name

Be careful : Static constants cannot be generic

Generic methods

grammar : return type

 

public class MyGenericMethod{
// Generic methods
public <T> T show(T t){
  sout(" Generic methods " + t);
  return t;
}
}

// call
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show(" character string ");// The automatic type is string
myGenericMethod.show(200);// integer type
myGenericMethod.show(3.14);// double type

Generic set

Concept : Parameterized types 、 Type safe set , Mandatory collection elements must be of the same type

characteristic :

  • Compile time to check , Instead of throwing an exception at runtime

  • During the interview , There is no need to type cast ( Unpacking )

  • Applications cannot assign values to each other between generics , There is no polymorphism in generics

  • package com.pc.zjs01;

    import com.pc.zjs.Student;

    import java.util.ArrayList;
    import java.util.Iterator;

    public class Demo03 {
       public static void main(String[] args) {
           ArrayList<String> arrayList=new ArrayList();
           arrayList.add("xxx");
           arrayList.add("yyy");
    //       arrayList.add(10);
    //       arrayList.add(20);

           for(Object object:arrayList){
               String str=(String)object;
               System.out.println(str);
          }
           ArrayList<Student> arrayList2=new ArrayList<Student>();
           Student s1=new Student(" Lau Andy ",20);
           Student s2=new Student(" Aaron Kwok ",22);
           Student s3=new Student(" Tony Leung ",18);
           arrayList2.add(s1);
           arrayList2.add(s2);
           arrayList2.add(s3);

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

      }
    }

Set aggregate

characteristic : disorder 、 No subscript 、 Element is not repeatable

Method : All inherited from Collection The method in

increase 、 Delete 、 Traverse 、 Judgment and collection Agreement

package com.pc.zjs02;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
* test set Use of interfaces
* Feature disorder, no subscript, no repetition
*/
public class Demo01 {
   public static void main(String[] args) {
       // Create set
       Set<String> set=new HashSet<>();
       //1 Add data
       set.add(" millet ");
       set.add(" Apple ");
       set.add(" Huawei ");
       System.out.println(" The number of data "+set.size());
       System.out.println(set.toString());
       //2 Delete data
//       set.remove(" millet ");
//       set.clear();

       //3 Traverse
       //3.1 Use enhancements for
       System.out.println("--- enhance for---");
       for(String string:set){
           System.out.println(string);
      }
       //3.2 Using Iterators
       Iterator<String> it = set.iterator();
       while (it.hasNext()){
           System.out.println(it.next());
      }
       //4 Judge
       System.out.println(set.contains(" Huawei "));
       System.out.println(set.isEmpty());
  }
}

 

HashSet 【 a key 】

Storage structure : Hashtable ( Array + Linked list + Red and black trees )

package com.pc.zjs02;

import java.util.HashSet;
import java.util.Iterator;

/**
* HashSet Use of collections
* Storage structure : Hashtable ( Array + Linked list + Red and black trees )
*/
public class Demo02 {
   public static void main(String[] args) {
       // New collection
       HashSet<String> hashSet=new HashSet<String>();
       //1 Additive elements
       hashSet.add(" Lau Andy ");
       hashSet.add(" Tony Leung ");
       hashSet.add(" Lin ");
       hashSet.add(" Chow yun-fat ");
       hashSet.add(" Lau Andy ");// Adding duplicate elements doesn't work
       System.out.println(" Element number "+hashSet.size());
       System.out.println(hashSet.toString());
       //2 Remove elements
//       hashSet.remove(" Lau Andy ");
//       System.out.println(" After deleting "+hashSet.size());
       //3 Traverse
       //3.1 enhance for
       System.out.println("--- enhance for---");
       for(String string:hashSet){
           System.out.println(string);
      }
       //3.2 Using Iterators
       System.out.println("--- iterator ---");
       Iterator<String> it = hashSet.iterator();
       while (it.hasNext()){
           System.out.println(it.next());
      }
       //4 Judge
       System.out.println(hashSet.contains(" Aaron Kwok "));
       System.out.println(hashSet.isEmpty());
  }
}

 

stored procedure ( Repeat on the basis of )

  1. according to hashCode Calculate where to save , If the position is empty , Save directly , If not be empty , Take the second step

  2. Re execution equals Method , If equals by true, They think it's repetition , Otherwise form a linked list

    package com.pc.zjs02;

    import java.util.HashSet;
    import java.util.Iterator;

    /**
    * HashSet Use
    *(1) according to hashCode Calculate where to save , If the position is empty , Save directly , If not be empty , Take the second step
    * (2) Re execution equals Method , If equals by true, They think it's repetition , Otherwise form a linked list
    */
    public class Demo03 {
       public static void main(String[] args) {
           // Create set
           HashSet<Person> persons=new HashSet<>();
           //1 Add data
           Person p1=new Person(" Lau Andy ",20);
           Person p2=new Person(" Lin ",22);
           Person p3=new Person(" Tony Leung ",25);
           persons.add(p1);
           persons.add(p2);
           persons.add(p3);
           persons.add(p1);// Duplicate elements don't add
           persons.add(new Person(" Tony Leung ",25));// You can add

           System.out.println(" Element number "+persons.size());
           System.out.println(persons.toString());
           //2. Remove elements
    //       persons.remove(" Lau Andy ");
    //       persons.clear();
    //       persons.remove(new Person(" Lau Andy ",20));// It can be deleted because it has been rewritten hashcode,equals Method

           //3 Traverse
           //3.1 enhance for
           System.out.println("--- enhance for--");
           for(Person person:persons){
               System.out.println(person.toString());
          }
           //3.2 iterator
           System.out.println("--- iterator ---");
           Iterator<Person> it = persons.iterator();
           while (it.hasNext()){
               System.out.println(it.next());
          }
           //4 Judge
           System.out.println(persons.contains(new Person(" Lau Andy ",20)));
           System.out.println(persons.isEmpty());
      }
    }
    package com.pc.zjs02;

    public class Person {
       private String name;
       private int age;

       public Person() {
      }

       public Person(String name, int age) {
           super();
           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 int hashCode() {
           int n1=this.name.hashCode();
           int n2=this.age;
           return n1+n2;
      }

       @Override
       public boolean equals(Object obj) {
           if (this==obj){
               return true;
          }
           if(obj==null){
               return false;
          }
           if(obj instanceof Person){
               Person p=(Person)obj;
               if(this.name.equals(p.getName())&&this.age==p.getAge()){
                   return true;
              }
          }
           return false;
      }
    }

     

characteristic

  • be based on HashCode Calculation element storage location

    • utilize 31 This prime number , Reduce hash conflicts

      • 31 Improve execution efficiency 31 * i = (i << 5) - i Switch to shift operation

    • When the hash code stored in the element is the same , Would call equals Confirm , If the result is true, Then refuse the latter to deposit

New collection HashSet<String> hashSet = new HashSet<String>();

Additive elements hashSet.add( );

Remove elements hashSet.remove( );

Traversal operation

1. enhance for for( type type : hashSet)

2. iterator Iterator<String> it = hashSet.iterator( );

Judge hashSet.contains( ); hashSet.isEmpty();

TreeSet

characteristic

  • Based on the permutation order, the elements are not repeated

  • Realization SortedSet Interface , Automatically sort set elements

  • The type of the element object must implement Comparable Interface , Specify collation

  • adopt CompareTo Method to determine whether it is a repeating element

Storage structure : Red and black trees

Create set TreeSet<String> treeSet = new TreeSet<>()

Additive elements treeSet.add();

Remove elements treeSet.remove();

Traverse 1. enhance for 2. iterator

Judge treeSet.contains();

Add :TreeSet Use of collections

Comparator Realize custom comparison ( The comparator )

Comparable Comparable

package com.pc.zjs02;

import java.util.Iterator;
import java.util.TreeSet;

/**
* TreeSet Use
* Storage structure : Red and black trees
*/
public class Demo04 {
   public static void main(String[] args) {
       // Create set
       TreeSet<String> treeSet=new TreeSet<>();
       //1 Additive elements
       treeSet.add("xyz");
       treeSet.add("abc");
       treeSet.add("hello");
       System.out.println(" Element number "+treeSet.size());
       System.out.println(treeSet.toString());

       //2 Remove elements
//       treeSet.remove("xyz");
//       System.out.println(" After deleting "+treeSet.size());
//       treeSet.clear();
       //3 Traversing elements
       //3.1 enhance for
       System.out.println("--- enhance for---");
       for(String string:treeSet){
           System.out.println(string);
      }//3.2 iterator
       System.out.println("--- iterator ---");
       Iterator<String> it = treeSet.iterator();
       while (it.hasNext()){
           System.out.println(it.next());
      }
       //4 Judge
       System.out.println(treeSet.contains("abc"));
       System.out.println(treeSet.isEmpty());
  }
}
package com.pc.zjs02;

import java.util.Iterator;
import java.util.TreeSet;

/**
* Use treeset Save the data
* Storage structure : Red and black trees
* requirement : Elements have to implement comparable Interface ,compareTo() The return value of the method is 0, It is determined as a repeating element
*/
public class Demo05 {
   public static void main(String[] args) {
       // Create set
       TreeSet<Person> persons=new TreeSet<>();
       //1 Additive elements
       Person p1=new Person(" Lau Andy ",20);
       Person p2=new Person(" Lin ",22);
       Person p3=new Person(" Tony Leung ",25);

       persons.add(p1);
       persons.add(p2);
       persons.add(p3);
       System.out.println(" Element number "+persons.size());
       System.out.println(persons.toString());
       //2 Delete
//       persons.remove(new Person(" Tony Leung ",22));
//       persons.clear();
       //3 Traverse
       //3.1 enhance for
       System.out.println("--- enhance for---");
       for(Person person:persons){
           System.out.println(person);
      }
       //3.2 iterator
       System.out.println("--- iterator ---");
       Iterator<Person> it = persons.iterator();
       while (it.hasNext()){
           System.out.println(it.next());
      }
       //4 Judge
       System.out.println(persons.contains(p1));
       System.out.println(persons.isEmpty());
  }
}
package com.pc.zjs02;

public class Person implements Comparable<Person>{
   private String name;
   private int age;

   public Person() {
  }

   public Person(String name, int age) {
       super();
       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 int hashCode() {
       int n1=this.name.hashCode();
       int n2=this.age;
       return n1+n2;
  }

   @Override
   public boolean equals(Object obj) {
       if (this==obj){
           return true;
      }
       if(obj==null){
           return false;
      }
       if(obj instanceof Person){
           Person p=(Person)obj;
           if(this.name.equals(p.getName())&&this.age==p.getAge()){
               return true;
          }
      }
       return false;
  }

   // 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;
  }
}

TreeSet Case study

package com.pc.zjs02;

import java.util.Comparator;
import java.util.TreeSet;

/**
* demand : Use TreeSet The collection implements string sorting by length
* helloworld zhang lisi wangwu beijing xian nanjing
* Comparator Interface implementation customization comparison
*/
public class Demo06 {
   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("helloworld");
       treeSet.add("pingguo");
       treeSet.add("lisi");
       treeSet.add("zhangsan");
       treeSet.add("beijing");
       treeSet.add("cat");
       treeSet.add("nanjing");
       treeSet.add("xian");
       System.out.println(treeSet.toString());
  }
}

Map aggregate

Map Interface features

1.  Used to store arbitrary key value pairs (key - value)
2. key : disorder 、 No subscript 、 No repetition ( only )
3. value : disorder 、 No subscript 、 Allow repetition

Method :

1. V put(K key, V value)  Save objects to a collection , Associated key value 
2. Object get(Object key) Get the corresponding value according to the key
3. Set<K> Return all Key
4. Collection<V> values() Returns... Containing all values Collection aggregate
5. Set<Map.Entry<K, V>> Key value matching Set aggregate

Map Use of interfaces

package com.pc.zjs03;

import java.util.HashMap;
import java.util.Map;

/**
* Map Use of interfaces
* characteristic ;(1) Store key value pairs (2) Bonds cannot be repeated , Values can be repeated (3) disorder
*/
public class Demo01 {
   public static void main(String[] args) {
       // establish Map aggregate
       Map<String,String> map=new HashMap<>();
       //1. Additive elements
       map.put("cn", " China ");
       map.put("uk", " The British ");
       map.put("usa", " The United States ");
       map.put("cn", "zhongguo");
       System.out.println(" Element number "+map.size());
       System.out.println(map.toString());
       //2 Delete
//       map.remove("usa");
//       System.out.println(" After deleting "+map.size());
       //3. Traverse
       //3.1 Use keySet();
       System.out.println("---keySet---");
       //Set<String> keySet = map.keySet();
       for(String key:map.keySet()){
           System.out.println(key+"------"+map.get(key));
      }
       //3.2 Use entrySet() Method
       System.out.println("--- Use entrySet()---");
       //Set<Map.Entry<String, String>> entries = map.entrySet();
       for(Map.Entry<String,String> entry:map.entrySet()){
           System.out.println(entry.getKey()+"------"+entry.getValue());
      }
       //4 Judge
       System.out.println(map.containsKey("cn"));
       System.out.println(map.containsValue(" Thailand "));
  }
}

HashMap

Storage structure : Hashtable ( Array + Linked list + Red and black trees )

Use key Can make hashcode and equals As a repetition

increase 、 Delete 、 Traverse 、 The judgment is consistent with the above

Source code analysis summary :

  1. HashMap Just created ,table yes null, Save a space , When you add the first element ,table The capacity is adjusted to 16

  2. When the number of elements is greater than the threshold (16*0.75 = 12) when , Capacity expansion will be carried out , The size after expansion is twice the original size , The goal is to reduce the number of adjustment elements

  3. jdk1.8 When the length of each list >8 , And the number of array elements ≥64 when , Will be adjusted to a red black tree , The aim is to improve efficiency

  4. jdk1.8 When the list length <6 when Adjust to linked list

  5. jdk1.8 before , Insert in the head of a linked list , Then insert for the tail

    package com.pc.zjs03;

    import java.util.HashMap;
    import java.util.Map;

    /**
    * HashMap aggregate
    * Storage structure : Hashtable ( Array + Linked list + Red and black trees )
    * Use key Of hashcode and equals As a basis for repetition
    */
    public class Demo02 {
       public static void main(String[] args) {
           // Create set
           HashMap<Student,String> students=new HashMap<Student,String>();
           // Additive elements
           Student s1=new Student(" The Monkey King ",100);
           Student s2=new Student(" Pig eight quit ",101);
           Student s3=new Student(" Monk sha ",102);
           students.put(s1," Beijing ");
           students.put(s2," Shanghai ");
           students.put(s3," Hangzhou ");
           students.put(new Student(" Monk sha ",1002)," Hangzhou ");
           System.out.println(" Element number "+students.size());
           System.out.println(students.toString());

           //2 Remove elements
           students.remove(s1);
           students.clear();
           System.out.println(" After deleting "+students.size());
           //3 Traverse
           //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 Judge
           //System.out.println(students.containsKey(s1));
           System.out.println(students.containsKey(new Student(" The Monkey King ",100)));
           System.out.println(students.containsValue(" Hangzhou "));
      }
    }
    package com.pc.zjs03;

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

       public Student() {
      }

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

       public String getName() {
           return name;
      }

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

       public int getStuNo() {
           return stuNo;
      }

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

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

       @Override
       public int hashCode() {
           final int prime=31;
           int result =1;
           result=prime*result+((name==null)?0:name.hashCode());
           result=prime*result+stuNo;
           return result;
      }

       @Override
       public boolean equals(Object obj) {
          if(this==obj)
              return true;
          if(obj==null)
              return false;
          if(getClass()!=obj.getClass())
              return false;
          Student other=(Student) obj;
          if(name==null){
              if(other.name!=null)
                  return false;
          }else if(!name.equals(other.name))
              return false;
          if(stuNo!=other.stuNo)
              return false;
          return true;
      }

       @Override
       public int compareTo(Student o) {
           int n2=this.stuNo-o.getStuNo();
           return n2;
      }
    }


     

Hashtable

Thread safety , Slow operation efficiency ; Don't allow null As key or value

Properties

hashtable Subclasses of , requirement key and value All are string, It is usually used to read configuration files

TreeMap

Realized SortedMap Interface ( yes map Sub interface of ), It can be done to key Automatic sorting

package com.pc.zjs03;

import java.util.Map;
import java.util.TreeMap;

public class Demo03 {
   public static void main(String[] args) {
       // Create set
           TreeMap<Student,String> treeMap=new TreeMap<Student,String>();
           // Additive elements
           Student s1=new Student(" The Monkey King ",100);
           Student s2=new Student(" Pig eight quit ",101);
           Student s3=new Student(" Monk sha ",102);
           treeMap.put(s1," Beijing ");
           treeMap.put(s2," Shanghai ");
           treeMap.put(s3," Hangzhou ");
           System.out.println(" Element number "+treeMap.size());
           System.out.println(treeMap.toString());

           //2 Delete
//           treeMap.remove(new Student(" Pig eight quit ",101));
//           System.out.println(treeMap.size());
           //3 Traverse
           //3.1 Use keySet
           System.out.println("--- Use keySet()---");
           for(Student key:treeMap.keySet()){
                   System.out.println(key+"------"+treeMap.get(key));
          }
           System.out.println("--- Use entrySet()---");
           for (Map.Entry<Student,String> entry:treeMap.entrySet()){
                   System.out.println(entry.getKey()+"------"+entry.getValue());
          }
           //4 Judge
           System.out.println(treeMap.containsKey(new Student(" Monk sha ",102)));
  }
}

Collection Tool class

Concept : Collection tool class , It defines the common methods of collection besides access

Direct binary search int i = Collections.binarySearch(list, x); Index returned successfully

Other methods : copy Copy 、reverse reverse 、shuffle Upset

Add :

package com.pc.zjs03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
* demonstration Collection Use of tool class
*/
public class Demo04 {
   public static void main(String[] args) {
       List<Integer> list=new ArrayList<>();
       list.add(20);
       list.add(5);
       list.add(12);
       list.add(30);
       list.add(6);
       //sort Sort
       System.out.println(" Before sorting "+list.toString());
       Collections.sort(list);
       System.out.println(" After the sorting "+list.toString());

       //binarySearch
       int i= Collections.binarySearch(list,12);
       System.out.println(i);

       //copy Copy
       List<Integer> dest=new ArrayList<>();
       for (int k=0;k<list.size();k++){
           dest.add(0);
      }
       Collections.copy(dest,list);
       System.out.println(dest.toString());
       //reverse reverse
       Collections.reverse(list);
       System.out.println(" After reversing "+list);
       //shuffle Upset
       Collections.shuffle(list);
       System.out.println(" After the chaos "+list);
       // Add :list Turn it into an array
       System.out.println("---list Turn it into an array ---");
       Integer[] arr = list.toArray(new Integer[0]);
       System.out.println(arr.length);
       System.out.println(Arrays.toString(arr));
       // An array is converted to a collection
       System.out.println("--- An array is converted to a collection ---");
       String[] names={" Zhang San "," Li Si "," Wang Wu "};
       // Set is a restricted set , You can't add or delete
       List<String> list2=Arrays.asList(names);

       System.out.println(list2);
       Integer[] nums={100,200,300,400,500};
       List<Integer> list3 = Arrays.asList(nums);
       System.out.println(list3);

  }
}

summary

  • The concept of set :

    Object's container , Similar to arrays , It defines the common operation methods of multiple objects

  • List aggregate

    Orderly , There are subscript elements that can be repeated ,ArrayList,LinkedList,Vector

  • Set aggregate

    disorder , No subscript , Elements cannot be repeated HashSet,TreeSet

  • Map aggregate

    Store a pair of data , disorder , No subscript , Key is not repeatable , Values can be repeated HashMap,HashTable,TreeMap

  • Collections

Collection tool class , It defines the common methods of collection besides access

版权声明
本文为[Handsome cochlea]所创,转载请带上原文链接,感谢