Hashset使用2
package com.tiedandan.集合.泛型.set子接口;
import java.util.HashSet;
import java.util.Iterator;
//哈希列表,由数组加列表组成,无下标,不可重复
public class HashSetUse2 {
public static void main(String[] args) {
HashSet<Person> hashSet1 =new HashSet<>();
Person p1 = new Person("张铁蛋",666);
Person p2 = new Person("张铁蛋",555);
Person p3 = new Person("张铁蛋",444);
Person p4 = new Person("张铁蛋",333);
hashSet1.add(p1);
hashSet1.add(p2);
hashSet1.add(p3);
hashSet1.add(p4);
hashSet1.add(p3);//因为P3是重复定义的对象,hash列表不能有重复,所以只会执行一个添加对象操作
hashSet1.add(new Person("张铁蛋",444));//这种方法能添加一个P3,因为new的对象没有名字,所以无法判定为重复对象。
hashSet1.add(new Person("张铁蛋",444));//理论上可以添加无数个这样没有名字的对象,都不会判定重复。
System.out.println(hashSet1.toString());
Iterator<Person> lt = hashSet1.iterator();
//遍历.
while (lt.hasNext()){
Person s =lt.next();
System.out.println(s.toString());
}
}
}
package com.tiedandan.集合.泛型.set子接口;
public class Person {
private String name;
private int 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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
[Person{name='张铁蛋', age=444}, Person{name='张铁蛋', age=444}, Person{name='张铁蛋', age=555}, Person{name='张铁蛋', age=666}, Person{name='张铁蛋', age=333}, Person{name='张铁蛋', age=444}]
Person{name='张铁蛋', age=444}
Person{name='张铁蛋', age=444}
Person{name='张铁蛋', age=555}
Person{name='张铁蛋', age=666}
Person{name='张铁蛋', age=333}
Person{name='张铁蛋', age=444}