1、Set集合
Set集合中的对象不按特定方式排序,只是简单的将对象加入集合中。Set集合不能包含重复对象。
1、1Set接口
Set集合由Set接口和Set接口的实现类组成。
Method | Return | Describle |
add(Object obj) | boolean | 如果此Set集合中不存在此obj则将其添加到集合中 |
addAll(Colection coll) | boolean | 将coll添加到集合尾部 |
remove(Object obj) | boolean | 移除obj |
retainAll(Collection coll) | boolean | 只保存Set集合中包含在指定Collection集合中的内容 |
removeAll(Collection c) | boolean | 在Set集合中移除指定Collection中的元素 |
clear() | void | 清除Set |
iterator() | Iterator | 返回此Set中的元素上进行迭代的迭代器 |
size() | int | Set中元素数 |
isEmpty() | boolean | 空返回true |
Set接口的实现类常用的:
Set<String> collSet = new HashSet<String>();
Set<String> colSet = new TreeSet<String>();
example:
addAll()/iterator()
package sixteen;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
public class setaddAll {
public static void main(String[] args){
List list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("a");
//java.util.HashSet.HashSet<String>()
Set set = new HashSet<String>();
//Set集合中不允许有重复字符,可以用此方法删去重复字符
set.addAll(list);
Iterator<String> it = set.iterator();
System.out.println("Set is :");
while(it.hasNext()){
System.out.println(it.next());
}
}
}
/*Set is :
a
b*/
HashSet
不保证Set的迭代顺序,不保证顺序不变。
example:
package sixteen;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class People {
private String name;
private long id;
public People(String name,long id){
this.name = name;
this.id = id;
}
public long getId(){
return id;
}
public void setId(){
this.id = id;
}
public String getName(){
return name;
}
public void setName(){
this.name = name;
}
public static void main(String[] args){
Set<People> hashSet = new HashSet<People>();
hashSet.add(new People("John",123));
hashSet.add(new People("Sam",456));
Iterator<People> it = hashSet.iterator();
System.out.println("Set is :");
while(it.hasNext()){
People person = it.next();
System.out.println(person.getName() + person.getId());
}
}
}
/*
* Set is :
John123
Sam456
*/