Java basics - Set collection implementation class

(1) Set collection implementation class features:

  • HashSet: unordered, not repeated, no index.
  • LinkedHashSet: ordered, not repeated, no index.
  • TreeSet: Sort, no repetition, no index.

 (2) HashSet set

1. The underlying principle:

  • The bottom layer of the HashSet collection adopts the data stored in the hash table.
  • The hash table is a structure with better performance for adding, deleting, modifying and querying data.

2. The composition of the hash table: 

  • After the start of JDK8, the bottom layer is composed of array + linked list + red-black tree.
  • Before JDK8, the bottom layer is composed of array + linked list.

3. Hash value:

  • It is the value of int type calculated by JDK according to the address of the object and according to certain rules.

4. API of Object class:

  • public int hashCode(): returns the hash value of the object.

5. The hash value characteristics of the object:

  • The hash value returned by calling the hashCode() method multiple times on the same object is the same.
  • By default, different objects have different hash values. 
  • public class HashDemo01 {
        public static void main(String[] args) {
            //1.获取对象的哈希值
            String name1 = "大大";
            System.out.println(name1.hashCode());//730336
            //同一个对象多次调用hashCode()方法返回的哈希值是相同的。
            System.out.println(name1.hashCode());//730336
    
            //默认情况下,不同对象的哈希值是不同的。
            String name2 = "小小";
            System.out.println(name2.hashCode());//754144
        }
    }
    

 (3) LinkedHashSet collection:

  • Ordered, no duplicates, no index.
  • Ordered: Ensure that the elements stored and retrieved are in the same order.
  • Principle: The underlying data structure is still a hash value, but each element has an additional double-linked list mechanism to record the order of storage.

 (4) TreeSet collection:

1.TreeSet overview features:

  • No duplicates, no index, sortable.
  • Sortable: Sort elements in ascending order (from small to large) by default.
  • The bottom layer of the TreeSet collection is sorted based on the data structure of the red-black tree, and the performance of addition, deletion, modification and query is better.
  • Note: The TreeSet collection must be sorted, and the elements can be sorted according to the specified rules.

2. TreeSet collection sorting rules:

  • For numeric types: Interge, Double, the official default is to sort in ascending order by size.
  • For string type: By default, sort by the number of the first character in ascending order.
  • For custom types such as Student objects, TreeSet cannot be sorted directly.
  • Note: If you want to use TreeSet to store custom types, you need to formulate collation rules

3. TreeSet collection storage object custom sorting rules:

  • Method 1: Make a custom class (such as a student class) implement the Comparable interface and rewrite the comparaTo method in it to formulate comparison rules.
  •  Method 2: The TreeSet collection has a parameter constructor, and the comparator object corresponding to the Comparator interface can be set to formulate comparison rules.
  • Note: If the objects stored in the TreeSet collection have implementation comparison rules, the collection also has its own comparator, and the built-in comparator is used for sorting by default.
    
    • Two ways to return value rules:
      • If it is considered that the first element is greater than the second element, return a positive integer.
      • If it is considered that the first element is smaller than the second element, return a negative integer.
      • If you think that the first element is equal to the second element and return 0, then the TreeSet collection will only retain one element, and the two are considered to be duplicates.
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
 * 目标:观察TreeSet集合的排序规则
 * TreeSet集合特点:不重复,无索引,可排序
 */
public class TreeSetDemo01 {
    public static void main(String[] args) {
        //1.对于数值类型:Interge,Double,官方默认按照大小进行升序排序。
        Set<Integer> sets = new TreeSet<>();
        sets.add(20);
        sets.add(25);
        sets.add(22);
        sets.add(19);
        System.out.println(sets);//[19, 20, 22, 25]

        //2.对于字符串类型:默认按照首字符的编号升序排序。
        Set<String> sets1 = new TreeSet<>();
        sets1.add("Aaa");
        sets1.add("Bbb");
        sets1.add("Aaa");
        sets1.add("DFG");
        sets1.add("CFG");
        System.out.println(sets1);//[Aaa, Bbb, CFG, DFG]

        //3.对于自定义类型如Student对象,TreeSet无法直接排序。想要使用TreeSet存储自定义类型,需要制定排序规则
        Set<Apple> apples = new TreeSet<>();
        apples.add(new Apple("苹果1","红色",9.9,500));
        apples.add(new Apple("苹果2","绿色",19.9,400));
        apples.add(new Apple("苹果3","青色",29.9,300));
        apples.add(new Apple("苹果4","黄色",39.9,200));

        /**
         * 自定义规则
         * 方式一:让自定义的类(如学生类)实现Comparable接口重写里面的comparaTo方法来制定比较规则。
          */
        System.out.println(apples);
        //[Apple{name='苹果4', color='黄色', price=39.9, weight=200}, Apple{name='苹果3', color='青色', price=29.9, weight=300}, Apple{name='苹果2', color='绿色', price=19.9, weight=400}, Apple{name='苹果1', color='红色', price=9.9, weight=500}]

//        /**
//         * 自定义比较规则    集合自带比较器
//         * 方式二:TreeSet集合有参数构造器,可以设置Comparator接口对应的比较器对象,来制定比较规则。
//         */
//        Set<Apple> apples1 = new TreeSet<>(new Comparator<Apple>() {
//            @Override
//            public int compare(Apple o1, Apple o2) {
                return o1.getWeight() - o2.getWeight();//升序
                return o2.getWeight() - o1.getWeight();//降序
                return Double.compare(o2.getPrice() , o1.getPrice());//降序
//                return Double.compare(o1.getPrice() , o2.getPrice());//升序
//            }
//        });

        //简化代码
        Set<Apple> apples1 = new TreeSet<>(( o1,  o2) -> Double.compare(o1.getPrice() , o2.getPrice()));

        apples1.add(new Apple("苹果1","红色",9.9,500));
        apples1.add(new Apple("苹果2","绿色",19.9,400));
        apples1.add(new Apple("苹果3","青色",29.9,300));
        apples1.add(new Apple("苹果4","黄色",39.9,200));
        System.out.println(apples1);
        //[Apple{name='苹果1', color='红色', price=9.9, weight=500}, Apple{name='苹果2', color='绿色', price=19.9, weight=400}, Apple{name='苹果3', color='青色', price=29.9, weight=300}, Apple{name='苹果4', color='黄色', price=39.9, weight=200}]


        //如果TreeSet集合存储的对象有实现比较规则,集合也自带比较器,默认使用自带的比较器排序

    }
}

class Apple implements Comparable<Apple>{
    private String name;
    private String color;
    private Double price;
    private int weight;

    public Apple() {
    }

    public Apple(String name, String color, Double price, int weight) {
        this.name = name;
        this.color = color;
        this.price = price;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

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

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                ", weight=" + weight +
                '}';
    }

    /**
     * 自定义制定规则:方式一
     * o1.compareTo(o2)
     * @param o
     * @return如果认为第一个元素大于第二个元素返回正整数即可。
     * 如果认为第一个元素小于第二个元素返回负整数即可。
     * 如果认为第一个元素等于第二个元素返回0即可,此时TreeSet集合只会保留一个元素,认为两者重复。
     */
    @Override
    public int compareTo(Apple o) {
        //如:按照重量进行比较
        //return this.weight - o.weight;//会去掉重量重复的元素
        return this.weight - o.weight >= 0 ? 1 : -1;//可以保留重量重复的元素
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/130029294