Set container -- HashSet and common APIs, sethashsetapi
Set container features:
① The Set container is a Collection that does not contain repeated elements and contains at most one null element. It is opposite to the List container, and the Set container cannot guarantee the order of its elements;
② The implementation classes of the two most common Set interfaces are HashSet and TreeSet;
HashSet and common APIs
① HashSet extends AbstractSet and implements the Set interface;
② HashSet uses a hash table for storage;
③ Constructor:
A) HashSet ()
B) HashSet (Collection c)
C) HashSet (int capacity)
D) HashSet (int capacity, float fillRatio)
④ HashSet does not define any parent class or other methods provided by interfaces that exceed it;
⑤ The hash set does not ensure the order of its elements, because hash processing is usually not involved in sorting;
1 HashSet <String> data = new HashSet <String> (); 2 data. add ("Zhang San"); 3 data. add ("Li Si"); 4 data. add ("jay"); 5 data. add ("jack"); 6 data. add ("jay"); 7 System. out. println (data );
Output result:
[Li Si, Zhang San, jay, jack]
The second jay is not saved here;
Can print it out System. out. println (data. add ("jay");, the result shows that the first is true, and the second is false.
Write a Student class:
1 class Student{ 2 private String name; 3 private int age; 4 public Student(String name, int age) { 5 super(); 6 this.name = name; 7 this.age = age; 8 } 9 public String getName() {10 return name;11 }12 public void setName(String name) {13 this.name = name;14 }15 public int getAge() {16 return age;17 }18 public void setAge(int age) {19 this.age = age;20 }21 }
Add and output in main method
1 HashSet <Student> stuSet = new HashSet <Student> (); 2 System. out. println (stuSet. add (new Student ("James", 20); 3 System. out. println (stuSet. add (new Student ("Li Si", 30); 4 System. out. println (stuSet. add (new Student ("James", 20); 5 System. out. println (stuSet. size (); 6
Output result:
True
True
True
3
It can be seen that new Student ("Zhang San", 20) has been created twice. If you want to create the same word only once, you need to reconstruct the hashCode and equals methods.
As follows:
1 @Override 2 public int hashCode() { 3 final int prime = 31; 4 int result = 1; 5 result = prime * result + age; 6 result = prime * result + ((name == null) ? 0 : name.hashCode()); 7 return result; 8 } 9 @Override10 public boolean equals(Object obj) {11 if (this == obj)12 return true;13 if (obj == null)14 return false;15 if (getClass() != obj.getClass())16 return false;17 Student other = (Student) obj;18 if (age != other.age)19 return false;20 if (name == null) {21 if (other.name != null)22 return false;23 } else if (!name.equals(other.name))24 return false;25 return true;26 }
Execute again and output the result:
True
True
False
2
Summary: The underlying data of the HashSet internal operations is HashMap, But we operate on the key of HashMap;