[Learning] Java Set collection, Collections Tools

Set interface extends Collection Interface
Set interface features:
1. does not allow duplicate storage elements
2 not indexed, indexed no method can not be used for normal loop through
HashSet set Implement Set interface
HashSet features:
storage 1. allowed repeated elements
2. no indexing, no method with an index is not used for looping through an ordinary
3 is an unordered collection, storage and order of the elements may be inconsistent extraction elements
4. the bottom structure is a hash table ( query speed is very fast)

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Demo01Set {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        // 使用add方法往集合中添加元素
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(4);
        Iterator<Integer> it = set.iterator();
        while (it.hasNext()) {
            Integer n = it.next();
            System.out.println(n);
        }

        for (Integer n : set) {
            System.out.println(n);
        }
    }
}

Hash values: is a decimal integer, is given (that is, the address value of the object by the random system, is a logical address, the address is simulated to obtain physical address data is not actually stored in
a method of the Object class, may be obtained the hash value of the object
int hasCode () returns the hash code value for this object
hasCode source method:

public native int hashCode();
native:代表该方法调用的是本地操作系统的方法

HashSet store the custom type elements
set collection holds the unique elements:
Storage elements (String, Integer, ... Student.Person), must be rewritten hasCode method and the equals method
Requirements:
with the same name with his age, treated as the same person, can only be stored once
Here Insert Picture Description

import java.util.Objects;

class Person {
    private String name;
    private int age;

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

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

    public Person() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
public class Demo04HashSetSavePerson {
    public static void main(String[] args) {
        HashSet<Person> set = new HashSet<>();
        Person p1 = new Person("小仙女",19);
        Person p2 = new Person("小美女",18);
        Person p3 = new Person("小美女",18);

        System.out.println(p1.hashCode()); // 722193131
        System.out.println(p2.hashCode()); // 734175839
        System.out.println(p3.hashCode()); // 734175839

        System.out.println(p2==p3); // false
        System.out.println(p2.equals(p3)); // true
        set.add(p1);
        set.add(p2);
        set.add(p3);
        System.out.println(set); //[Person{name='小仙女', age=19}, Person{name='小美女', age=18}]
    }
}

LinkedHashSet set of features:
the bottom layer is a hash table (array + list / black tree) + list: a multi-chain (sequential recording storage elements), to ensure orderly element

Variable parameters: characteristic appears after a new JDK1.5
used provided:
When the process parameter list data type has been determined, but the number of parameter uncertainty, can use variable parameters
using the format: Method used when defining
修饰符 返回值类型 方法名(数据类型...变量名){}
a variable parameter principle:
variable parameter is a bottom array, depending on the number of parameters passed, creates an array of different lengths, to store these parameters
the number of parameters passed, and may be 0 (no transmission), a plurality of 1,2, ...
Notes variable parameters:
the argument list 1. a method, only one variable parameter
2. If the end of the method has multiple parameters, then the variable parameters must be written in the parameter list

public class Demo01VarArgs {
    public static void main(String[] args) {
        int i = add(12,12);
        System.out.println(i);
    }
    /*
    定义计算(0-n)整数和的方法
    已知:计算整数的和,数据类型已经确定int
    但是参数的个数不确定,不知道要计算几个整数的和,就可以使用可变参数
     */
    public static int add(int...arr){
        //System.out.println(arr);
        int sum = 0;
        for (int i : arr) {
            sum =  sum + i;
        }
        return sum;
    }
//    public static int add(int a,int b){
//        return a+b;
//    }
}

Collections is a collection of tools for the collection operation. As part of the method
-public static <T> boolean addAll(Collection<T>c,T...elements):往集合中添加一些元素
-public static void shuffle(List<?> list) 打乱集合顺序

public static void sort (List list) to rank the set, the default is ascending
Note:
the Sort using premise
Are ordered set of elements stored inside, you must implement Comparable, rules interface methods defined ordered rewriting compareTo

Comparable collation interface:
own (this) - Parameters: Ascending

public static void sort (List list, Comparator <super T?>): The elements in the collection sorted according to the specified rules

Comparator and Comparable differences
Comparable: own (this) and others (parameters) comparison, they need to implement the Comparable interface, rewrite the rules of comparison compareTo method
Comparator: find the equivalent of a third-party referee to compare two

Comparator rules:
O1-O2 ascending, descending and vice versa

Published 19 original articles · won praise 20 · views 712

Guess you like

Origin blog.csdn.net/sy140823/article/details/104907990