廖雪峰Java5集合-4Set-1使用Set
集合
Set
- boolean add(E e)
- boolean remove(Object o)
- boolean contains(Object o)
- int size()
public class Main {
public static void main(String[] args) throws IOException {
Set<String> aset = new HashSet<>();
System.out.println("1"+aset.add("tom"));
System.out.println("2"+aset.add("tom"));//重复添加失败,set不能存储重复元素
System.out.println("3"+aset.add("jerry"));
System.out.println("集合长度"+aset.size());
System.out.println("4"+aset.remove("jerry"));
System.out.println("5"+aset.remove("kitty"));
System.out.println("6"+aset.contains("tom"));
System.out.println("7"+aset.contains("jerry"));
}
}
## Set不保证有序:
* HashSet是无序的
* Tree Set是有序的
* 实现了SortedSet接口的是有序Set
```#java
public class Main {
public static void main(String[] args) throws IOException {
//HashSet不能保证有序
Set示例:利用set去除List中的重复元素
public class Main {
public static void main(String[] args) throws IOException {
List<String> list1 = Arrays.asList("pear","apple","banana","orange","apple","banana");
System.out.println(removeDuplicate(list1));
}
static List<String> removeDuplicate(List<String> list){
Set<String> set = new HashSet<>(list);
return new ArrayList<>(set);
}
}
替换为TreeSet,对元素进行排序
```#java
public class Main {
public static void main(String[] args) throws IOException {
List总结
- Set用于存储不重复的元素集合
- 放入Set的元素与作为Map的Key要求相同:正确实现equals()和hashCode()
- 利用Set可以去除重复元素
- 遍历SortedSet按照元素的排序顺序遍历,也可以自定义排序算法