Set接口基本结束
- 无序(添加和取出顺序不一致),没有索引
- 不允许重复元素,所以最多包含一个null
Set接口的常用方法
和List接口一样,Set接口也是Collection的子接口,因此,常用方法和Collection接口一样
Set接口遍历方法
同Collection接口的遍历方式一样,因为Set接口是Collection接口的子接口。
- 可以使用迭代器遍历
- 增强for循环
- 不能使用索引的方式来获取
public class SetMethod {
public static void main(String[] args) {
// 以Set 接口的实现类 HashSet 来讲解Set接口的方法
// Set 接口的实现类的对象(Set接口对象),不能存放重复的元素,可以添加一个null
// Set 接口对象存放数据是无序的(添加和取出顺序不一致)
// 注意:取出的顺序虽然不是添加的顺序,但他是固定的
Set set = new HashSet();
set.add("a");
set.add("b");
set.add("c");
set.add("b"); //重复
set.add("d");
set.add(null);
set.add(null);
System.out.println(set); //[null, a, b, c, d]
// 遍历方式
// 方式1:迭代器
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.print(next+","); //null,a,b,c,d,
}
//方式2:增强for循环
for (Object o :set) {
System.out.print(o+","); //null,a,b,c,d,
}
//不能使用普通for循环遍历,因为set接口对象不能通过索引来获取
}
}