介绍完了List接口,我们来看看Set接口。Set接口:内部不可重复。Set接口有两个重要的实现类:HashSet和TreeSet。
HashSet属于无序,散列存放,需要重写equals和hashCode方法(hashCode相等,equals(内容)不一定相等;equals(内容)相等,hashCode一定相等)采用哈希算法实现的Set,HashSet的底层是用HashMap实现的,因此,查询效率高。由于采用HashCode算法直接确定元素的内存地址,增删效率也高。
TreeSet:有序、依靠Comparable接口排序,重写了compareTo方法。
HashSet的两种遍历方式:
System.out.println("=======iterator==========");
Iterator<String> it=str.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("=======增强for循环==========");
for(String temp:str){
System.out.println(temp);
}
TreeSet的两种遍历方式:
Iterator<String> it=set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
for(String str:set){
System.out.print(str+" ");
}
HashSet属于无序,散列存放,需要重写equals和hashCode方法(hashCode相等,equals(内容)不一定相等;equals(内容)相等,hashCode一定相等)采用哈希算法实现的Set,HashSet的底层是用HashMap实现的,因此,查询效率高。由于采用HashCode算法直接确定元素的内存地址,增删效率也高。
TreeSet:有序、依靠Comparable接口排序,重写了compareTo方法。
HashSet的两种遍历方式:
System.out.println("=======iterator==========");
Iterator<String> it=str.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("=======增强for循环==========");
for(String temp:str){
System.out.println(temp);
}
TreeSet的两种遍历方式:
Iterator<String> it=set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
for(String str:set){
System.out.print(str+" ");
}