JavaSE-集合(Set)
Set
基本API
public class Demo6 {
public static void main(String[] args) {
/**
* API
* 增加: add() addAll()
* 删除: clear() remove() removeAll()
* 修改:
* 查询: hashCode() contains() size()
* 判断: isEmpty() equals()
*/
Set set = new HashSet();
set.add(12);
set.add(1);
set.add(9);
set.add(30);
set.add(12);
set.add(8);
System.out.println(set.contains(12)); //=> true
System.out.println(set.hashCode()); //=> 60
System.out.println(set.size()); //=> 5
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+"\t"); //=> 1 8 9 12 30
}
}
}
HashSet 实现类
特点:唯一且无序。
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class Test{
public int num;
public String str;
public Test(int num, String str) {
this.num = num;
this.str = str;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Test)) return false;
Test test = (Test) o;
return num == test.num && str.equals(test.str);
}
@Override
public int hashCode() {
// 获取哈希码
return Objects.hash(num, str);
}
@Override
public String toString() {
return "Test{" +
"num=" + num +
", str='" + str + '\'' +
'}';
}
}
public class Demo4 {
public static void main(String[] args) {
Set<Integer> set = new HashSet<Integer>();
set.add(120);
set.add(212);
set.add(1);
set.add(1);
set.add(450);
set.add(511);
System.out.println(set); //=> [1, 2, 3, 4, 5]
System.out.println(set.size()); //=> 5
Set<String> set2 = new HashSet<String>();
set2.add("hello");
System.out.println(set2.add("world")); //=> true
System.out.println(set2.add("world")); //=> false
System.out.println(set2); //=> [world, hello]
System.out.println(set2.size()); //=> 2
Set set3 = new HashSet();
set3.add(new Test(12,"XIAOMING"));
set3.add(new Test(13,"XIAOHUA"));
set3.add(new Test(13,"XIAOMING") );
System.out.println(set3.add(new Test(12, "XIAOMING"))); //=> false
System.out.println(set3); //=> [Test{num=13, str='XIAOHUA'}, Test{num=13, str='XIAOMING'}, Test{num=12, str='XIAOMING'}]
System.out.println(set3.size()); //=> 3
}
}
源码分析:
经过上述测试发现放入String,Integer类型的数据都没有问题,都遵照HashSet的特点,但是放入自定义引用类型数据就不行了?解决:自定义类必须重写equals、hashCode方法。
底层原理分析:以Intege