Set接口方法
-
Set接口基本介绍
-
无序(添加和取出的顺序不一致),没有索引
-
不允许重复元素,所以最多包含一个null
-
Jdk API中常用Set接口的是实现类有TreeSet、HashSet
-
-
Set接口的遍历方式
-
可以使用迭代器
-
增强for循环
-
不能使用索引的方式来获取
-
import java.util.HashSet;
import java.util.Iterator;
public class HashSet01 {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("Jack");
hashSet.add("Tom");
hashSet.add("CiCi");
hashSet.add(null);
hashSet.add("XiXi");
hashSet.add(null);
hashSet.add("Rose");
System.out.println(hashSet);
//迭代器遍历集合
Iterator iterator = hashSet.iterator();
while(iterator.hasNext()){
Object next = iterator.next();
System.out.print(next+" ");
}
System.out.println();
//增强for循环遍历集合
for(Object o : hashSet){
System.out.print(o+" ");
}
}
}
/*
运行结果:
[null, Tom, Rose, XiXi, Jack, CiCi]
null Tom Rose XiXi Jack CiCi
null Tom Rose XiXi Jack CiCi
}
*/
HashSet全面说明
-
HashSet全面说明
-
HashSet实现了Set接口
-
可以存放null值,但是只能有一个null
-
HashSet不保证元素的是有序的,取决于hash后,在确定索引的结果
-
不能有重复元素/对象,
-
HashSet实际上是HashMap
-
public HashSet() {
map = new HashMap<>();
}
import java.util.HashSet;
public class HashSet02 {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
//添加元素
System.out.println(hashSet.add("Jack"));
System.out.println(hashSet.add("Jack"));
System.out.println(hashSet.add("CiCi"));
System.out.println(hashSet.add(new Nodes("Tom")));
System.out.println(hashSet.add(new Nodes("Tom")));
//输出
System.out.println(hashSet);
}
}
class Nodes{
private String name;
public Nodes(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Nodes{" +
"name='" + name + '\'' +
'}';
}
}
/*
运行结果:
true
false
true
true
true
[Nodes{name='Tom'}, Nodes{name='Tom'}, Jack, CiCi]
1.不能添加重复的元素
*/