Java collection framework (3)-Set interface

Collection interface two (Set interface):

1. Set: store unordered, non-repeatable collections, the bottom is a linked list

Set interface implementation class:

Insert picture description here
1. HashSet: As the main implementation class of the set interface, the thread is not safe and can store null values
2. LinkedHashSet: As a subclass of HashSet, when traversing its internal data, it can be traversed in the order of addition. High
3. TreeSet: You can sort according to the specified attributes of the added object

to sum up

1. There are no additional methods defined in the Set interface, and they are all methods declared in the Collection used.
2. Requirement 1: If you want to add data in Set, the class in which it is located must rewrite hashCode () and equals () –> generally use shortcut to generate
requirement 2: Rewrite hashCode () and equals () as much as possible Consistency: equal objects must have the same hash value
1) For ==, if it acts on a variable of a basic data type, directly compare whether the stored "value" is equal;
if it acts on a variable of a reference type, then compare It is the address of the object pointed to
2) For the equals method, note that the equals method cannot be applied to variables of the basic data type.
If the equals method is not rewritten, the address of the object pointed to by the variable of the reference type is compared;
If classes such as String and Date rewrite the equals method, the content of the pointed-to object is compared.

Second, the implementation process of Set

Set: store unordered, non-repeatable set (HashSet)
1. Disorder: not equal to randomness.
The stored data is not added in the order of the array index in the underlying array, but is determined according to the hash value of the data.

2. Non-repeatability: to ensure that the added element can not return true when judged according to equals (). That is: there can be only one of the same element.
3. Add the elements of the process: the underlying HashSet with an example: array + list (jdk7)
method we add elements to a HashSet, the first call HashCode a class of the element (), the elements of a hash value is calculated,
this ha Xixi then calculates the storage position of the array at the bottom of the HashSet (that is, the index position) through an algorithm to determine
whether there is an element at this position in the array:
if there is no element at this position, a is added successfully. —> Case 1
If there is another element b at this position (or there are multiple elements in the form of a linked list), then compare the hash values ​​of element a and element b:
if the hash values ​​are different, element a is added successfully—> case 2
If the hash value is the same, and then calling the equals () method of the class of element a
equals () returns true, then the addition of element a fails.
If equals () returns false, element a is added successfully. —> Case 3
For case 2 and case 3 where the addition is successful: element a already exists. The data at the specified index position is stored in the form of a linked list.
Jdk 7: element a is placed in the array, pointing to the original element (header insertion)
jdk 8: original element in the array, the element point a (tail addition)
summary: perturbed

Insert picture description here

   @Test
    public void  test(){
        Set set = new HashSet();
        set.add(123);
        set.add(123);
        set.add(456);
        set.add("AA");
        set.add("AA");
        set.add("BB");
        set.add(new Person("Tom",22));
        set.add(false);

        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.print(iterator.next() +"\t");
            //AA	BB	Person{name='Tom', age=22}	false	456	123
        }

Three, the use of LinkedHashSet

LinkedHashSet as a subclass of HashSet, while adding data, it also maintains two references, recording the previous data and the latter data

Advantages: high efficiency for frequent traversal operations

    @Test
  public void  test1(){
      Set set = new LinkedHashSet();
      set.add(123);
      set.add(123);
      set.add(456);
      set.add("AA");
      set.add("AA");
      set.add("BB");
      set.add(new Person("Tom",22));
      set.add(false);

      Iterator iterator = set.iterator();
      while(iterator.hasNext()){
          System.out.print(iterator.next() +"\t");
         //123	456	AA	BB	Person{name='Tom', age=22}	false
      }
  }

Four, the use of TreeSet

Insert picture description here
1. The data added to the TreeSet requires objects of the same class
2. Two sorting methods: natural sorting (implementing the Comparable interface in the use class to override the compareTo method) and custom sorting
3. Natural sorting: comparing two objects The same standard is: compareTo () returns 0, not equals ()

  @Test
    public void  test3(){
        TreeSet set = new TreeSet();

        //错误
//        set.add(123);
//        set.add(123);
//        set.add(456);
//        set.add("AA");
//        set.add("AA");
//        set.add("BB");
//        set.add(new Person("Tom",22));
//        set.add(false);
        //一
//        set.add(133);
//        set.add(456);
//        set.add(-145);
//        set.add(12);
//        set.add(6);
        //二
        //  //详细可见Java集合框架(一)-----Collection接口中的Person类
        set.add(new Person("Tom",23));
        set.add(new Person("FAS",15));
        set.add(new Person("SDF",45));
        set.add(new Person("WER",32));
        set.add(new Person("AF",20));
        //如果compareTo没有重写年龄的话,就只会有一个对象
        set.add(new Person("AF",50));

        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.print(iterator.next() +"\t");
        }
    }

4. Custom ordering of TreeSet The
standard for comparing whether two objects are the same is: compare () of Comparator returns 0, not equals ()

 @Test
   public void  test4() {
       Comparator com = new Comparator() {
           //按照年龄从小到大排列
           @Override
           public int compare(Object o1, Object o2) {
               if (o1 instanceof Person && o2 instanceof Person){
                   Person p1 = (Person)o1;
                   Person p2 = (Person)o2;
                   return Integer.compare(p1.getAge(),((Person) o2).getAge());
               }else {
                   throw new RuntimeException("输入的类型不匹配!");
               }
           }
       };

       TreeSet set = new TreeSet(com);
       set.add(new Person("Tom",23));
       set.add(new Person("FAS",15));
       set.add(new Person("SDF",45));
       set.add(new Person("AEE",45));
       set.add(new Person("WER",32));
       set.add(new Person("AF",20));
       //如果compareTo没有重写年龄的话,就只会有一个对象
       set.add(new Person("AF",50));

       Iterator iterator = set.iterator();
       while(iterator.hasNext()){
           System.out.println(iterator.next());
       }
   }
Exercise
  public static List duplicateList(List list){
      HashSet set =  new HashSet();
      set.addAll(list);
      return new ArrayList(set);
  }
  @Test
  public void test5(){
      List list = new ArrayList();
      list.add(new Integer(1));
      list.add(new Integer(2));
      list.add(new Integer(2));
      list.add(new Integer(3));
      list.add(new Integer(3));
      List list1 = duplicateList(list);
      for (Object integer : list1){
          System.out.println(integer);
      }
  }
  @Test
  public void test6(){
      HashSet set = new HashSet();
      Person p1 = new Person("AA",1001);
      Person p2 = new Person("BB",1002);

      set.add(p1);
      set.add(p2);

      p1.name = "CC";
      set.remove(p1);
      System.out.println(set);

      set.add(new Person("CC",1001));
      System.out.println(set);
      set.add(new Person("AA",1001));
      System.out.println(set);
  }
}
Published 19 original articles · praised 0 · visits 481

Guess you like

Origin blog.csdn.net/weixin_43244120/article/details/105497112