Set接口
set接口是继承自Collection的子接口,特点是元素不重复,存储无序。
在set接口的实现类中添加重复元素是不会成功的,判断两个元素是否重复根据元素类重写的hashCode()和equals()方法。
Set<String> stu1 = new HashSet<String>();
stu1.add("ab");
stu1.add("ac");
stu1.add("bc");
stu1.add("ba");
stu1.add("ba");
for (String s : stu1) {
System.out.println(s);
}
1、实现类HashSet
HashSet实现 Set 接口,由哈希表(底层由 HashMap 实现)支持。它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用null元素。HashSet保证元素唯一。
2、实现类TreeSet
TreeSet基于 TreeMap 的 NavigableSet 实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。
排序方式完全取决于使用的构造方法。
使用元素的自然顺序对元素进行排序(自然排序)
public class student {
private String name;
private String id;
public student (String name,String id) {
this.name=name;
this.id=id;
}
public String tostring () {
return id+":"+name;
}
public int hashcode(){
return id.hashCode();
}
public boolean eqials(Object obj) {
if(this==obj)
return true;
return false;
}
}
public class example {
public static void main(String[] args) {
HashSet<student> set=new HashSet<student>();
student stu1=new student("1","jack");
student stu2=new student("2","rose");
student stu3=new student("1","jack");
set.add(stu1);
set.add(stu2);
set.add(stu3);
System.out.println(set);
}
}
本文深入探讨了Set接口及其两种主要实现类HashSet和TreeSet的特点。HashSet由哈希表支持,不保证迭代顺序,允许null元素,而TreeSet则基于元素的自然顺序或自定义Comparator进行排序。
161

被折叠的 条评论
为什么被折叠?



