各位看官们,大家好,上一回中咱们说的是Java中类集之Queue的例子,这一回咱们说的例子是Java中的类集之Set
。闲话休提,言归正转。让我们一起Talk Android吧!
看官们,我们在前面章回中对Java中的类集做了概述性的介绍,这一回中我们将对类集中具体的接口和类进行介绍,这一回主要介绍Set
接口和它的实现类HashSet
。
这个Set
可以理解为集合,它与List
和Queue
最大的不同点在于,它里面存放的元素不能有重复。它有两个常用的实现类:HashSet和TreeSet
。
集合主要用来存放数据,因此只提供了添加和删除数据的方法:add(obj),remove(Obj)
,这里的obj表示集合中的元素。如果添加或者删除成功时返回true否则返回false。因为集合中不能有重复的元素,所以有必要在添加元素时判断是否添加成功。添加进去的元素存放在哪个位置由集合来确定,因此不能确定被添加元素的具体位置。鉴于这个原因set不支持像链表一样按照索引添加/删除元素。
另外,clear()
方法用来清空集合中所有的元素,清空后会变成空集合。与List
和Queue
接口相比,Set
接口提供的方法不多,不过我们还是使用文字结合代码的方式来演示如何使用它们。下面是具体的代码,请参考:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class setEx {
public static void main(String args[]){
// init set
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 10; ++i) {
// set.add(new Integer(i+1));
set.add((i + 1));
}
// show size of set ,and content of set
System.out.println("size of set: " + set.size());
for (Integer i : set)
System.out.print(i + " ");
System.out.println("\nset: " + set);
// delete the content of set,this is based on content of set
if(set.remove(9)) {
System.out.println("after removing the content 9. set: " + set);
} else {
System.out.println("removing the content 9 failed.");
}
// delete the same content of set,it is failed to remove
if(set.remove(9)) {
System.out.println("after removing the content 9. set: " + set);
} else {
System.out.println("removing the content 9 failed.");
}
// add the same content of set,it is failed to add
if(set.add(9)) {
System.out.println("after adding the content 9. set: " + set);
} else {
System.out.println("adding the content 9 failed.");
}
// add the content of set,this is based on content of set
if(set.add(9)) {
System.out.println("after adding the content 9. set: " + set);
} else {
System.out.println("adding the content 9 failed.");
}
// change set to array
Integer[] array = set.toArray(new Integer[] {});
System.out.println("change set to array: " + Arrays.toString(array));
// add the content of set,this is based on content of set
set.clear();
System.out.println("after clearing the set: " + set);
}
}
下面是程序的运行结果,请参考:
size of set: 10
1 2 3 4 5 6 7 8 9 10
set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after removing the content 9. set: [1, 2, 3, 4, 5, 6, 7, 8, 10]
removing the content 9 failed.
after adding the content 9. set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
adding the content 9 failed.
change set to array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after clearing the set: []
各位看官,关于Java中类集之Set的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!