特点:元素无序,不可重复
1.添加元素
set.add("tanlei");
set.addAll(Arrays.asList(44,"磊","磊"));
2.删除元素
set.remove("tanlei");
set.removeAll(Arrays.asList(44,"磊","磊"));
3.清空集合中的元素
set.clear();
4.遍历(两种方式遍历)
for(Object object:set) { System.out.println(object); } Iterator iterator=set.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); }
5.Set中元素按照自定义排序方式排序--匿名实现类 实现Comparator接口
TreeSet treeSet=new TreeSet(new MyComparator()); treeSet.add("A"); treeSet.add("bb"); treeSet.add("FDD"); treeSet.add("cc"); System.out.println(treeSet); private static class MyComparator implements Comparator{ /* * o1>o2 1 * o1==o2 0 * o1<o2 -1 * */ @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub return o1.hashCode()-o2.hashCode(); } }