1、API介绍
2、功能方法(与Collections接口提供方法一致)
HashSet类
1、API介绍
2、构造方法
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Demo7_HashSet {
public static void main(String[] args) {
//构造方法
//.HashSet() 使用默认集合大小为16,默认负载因子为0。75
Set set = new HashSet();
System.out.println(set);//[]
//.HashSet(int) 自定义集合大小,使用默认负载因子为0.75
Set set2 = new HashSet(100);
System.out.println(set);//[]
//.HashSet(int,float) 自定义集合大小和负载因子大小
Set set3 = new HashSet(100,0.5f);
System.out.println(set3);
//.HashSet(Collection) 初始化集合元素
Collection<String> col = new ArrayList();
col.add("100");
Set set4 = new HashSet(col);
System.out.println(set4);//[100]
}
}
3、功能方法(与Set接口功能方法一致)
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Demo7_HashSet {
public static void main(String[] args) {
//method_构造方法();
Set<String> set4 = new HashSet();
set4.add("abc");
set4.add("ccc");
boolean dde = set4.add("dde");//true
System.out.println(dde);
boolean abc = set4.add("abc");//false
System.out.println(abc);
System.out.println(set4);//[ccc, abc, dde]
//特点1:HashSet集合元素不重复
//特点2:Set接口集合无序
}
}
4、自定义对象唯一性
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
class Human {
String name;
Integer age;
public Human(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Human{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int hashCode() {
//如何重写hashCode? 如果所有属性值都相同则返回相同地址>>返回地址一定与属性相联系
return name.hashCode() * 7 + age * 11;
}
@Override
public boolean equals(Object obj) {
//如何重写equals? >>>相同与否要与属性相联系
if (obj == null) {
return true;//返回相同
}
if (this == obj) {
return true;//返回相同
}
if (obj instanceof Human) {
Human human = (Human) obj;
return this.name.equals(human.name) ? this.age == human.age : false;
}
return true;
}
}
public class Demo7_HashSet {
public static void main(String[] args) {
Set<Human> set = new HashSet<>();
Human h1 = new Human("唐伯虎", 20);
Human h2 = new Human("秋香", 19);
Human h3 = new Human("石榴姐", 30);
set.add(h1);
set.add(h2);
set.add(h3);
Human h4 = new Human("唐伯虎", 20);
set.add(h4);
//问题:Set集合无法确保自定义对象是唯一呢?地址不同
//解决:重写hashCode()和equals()
}
}