一.Set接口描述的是一比较简单的集合存储的是一组唯一、无序的对象;Set接口常用的实现类有HashSet,常用的方法:
1.添加指定元素:
HashSet set = new HashSet(); //用来存储数组
NewsTitle a1 = new NewsTitle(1, "dsfs ", "wr");
NewsTitle a2 = new NewsTitle(2, "dsf ", "wr");
NewsTitle a3 = new NewsTitle(3, "ds ", "wr");
NewsTitle a4 = new NewsTitle(4, "ds ", "wr");
set.add(a1);
set.add(a2);
set.add(a3);
2.判断是否有元素,不包含元素则为true;
System.out.println(set.isEmpty());
3.判断是否包含指定元素,包含则返回true;
System.out.println(set.contains(a1));
4.移除指定元素
set.remove(a2);
二.迭代器(Iterator接口):实现集合的遍历
有两个方法:
hasNext():判断是否存在下一个可访问的元素,如果还有元素可以进行迭代,额返回true;
while (itor.hasNext()) { //hasNext();判断是不是存在下一个元素;
next():返回要访问的下一个元素(注意:凡是Collection 接口派生而来的接口或者类,都实现了iterate()方法,iterate()方法返回的是一个 Iterator对象!我们可以给对象去一个名字进行定义)
Iterator itor = set.iterator(); //collection 接口的iterator()方法;
NewsTitle title = (NewsTitle) itor.next();
System.out.println(title.getAuthor());
本文详细介绍了Java集合框架中的Set接口,包括其无序、唯一特性和常用的实现类如HashSet。通过实例展示了如何添加、判断元素以及移除元素的操作。同时,文章还讲解了迭代器Iterator的使用,包括hasNext()和next()方法,用于遍历并访问集合中的元素。
944

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



