package com.binbin.jaEE;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.junit.Before;
public class JaEE02 {
public static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
list.add("李四");
list.add("李林");
list.add("李林");
list.add("张三");
list.add("Sb");
List<String> tmp = new ArrayList<String>(new HashSet<String>(list));
System.err.println(tmp);
}
}
- 它存储唯一元素并允许空值
- 依据对象的hashcode来确定该元素是否存在
- 由HashMap支持
- 不保持插入顺序
- 非线程安全
- 性能参数:初始容量,负载因子
- 默认值: 初始容量16,负载因子0.75
- 示例:new HashSet<>(20, 0.5f);
HashSet底层由HashMap实现
HashSet的值存放于HashMap的key上
HashMap的value统一为PRESENT
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + S_age;
result = prime * result + S_id;
result = prime * result + ((S_name == null) ? 0 : S_name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Setpojo other = (Setpojo) obj;
if (S_age != other.S_age)
return false;
if (S_id != other.S_id)
return false;
if (S_name == null) {
if (other.S_name != null)
return false;
} else if (!S_name.equals(other.S_name))
return false;
return true;
}
package com.binbin.jaEE;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class JaEE02 {
@Test
public void Test01() {
Set<Setpojo> set=new HashSet<Setpojo>();
set.add(new Setpojo(1,"李四",13));
set.add(new Setpojo(1,"李四",13));
set.add(new Setpojo(2,"张桑",15));
set.add(new Setpojo(3,"张三",14));
for (Setpojo s : set) {
System.out.println(s);
}
}
}
package com.binbin.jaEE;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Test;
public class JaEE02 {
@Test
public void Test01() {
TreeSet<Setpojo> set=new TreeSet<Setpojo>(new Comparator<Setpojo>() {
@Override
public int compare(Setpojo o1, Setpojo o2) {
return o2.getS_age()-o1.getS_age();
}
});
set.add(new Setpojo(1,"李四",13));
set.add(new Setpojo(1,"李四",13));
set.add(new Setpojo(2,"张桑",15));
set.add(new Setpojo(3,"张三",14));
for (Setpojo s : set) {
System.out.println(s);
}
}
}
如图: