您的位置:首页 > 编程语言 > Java开发

JAVA | 52 - 类集框架 | Set 接口

2017-12-05 23:18 357 查看
Set 子接口只是简单地继承了 Collection 接口,所以并没有 get 方法。

Set 集合中没有重复元素,这一点是 Set 接口的特征。

HashSet 子类保存的内容是无序的,TreeSet 子类保存的内容自动排序。

在 java 开发中,首先选择的是 List 子接口, Set 子接口绝对不是首选,就算是要使用 Set 子类,也首选使用 HashSet 子类,因为可以回避排序。

Comparable 这种比较器大部分情况下只存在于 java 理论范畴内,例如要进行 TreeSet 子类的排序。

Set 子接口不论如何操作,都必须保持一个原则,数据不能重复。

import java.util.*;

class Book{
private String title;
private int price;
public Book(String title, int price){
this.title = title;
this.price = price;
}
@Override
public String toString() {
return this.title + " " + this.price;
}
@Override
public int hashCode() {
return Objects.hash(title, price);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Book other = (Book) obj;
return Objects.equals(this.title, other.title)
&& Objects.equals(this.price, other.price);
}
}
public class Main {
public static void main(String[] args) throws Exception{
// 设置了泛型,从而保证集合中所有的数据类型都一致
Set<Book> set = new HashSet <Book>();
set.add(new Book("java",100));
set.add(new Book("c",89));
set.add(new Book("c++",100));
set.add(new Book("python",100));
set.add(new Book("python",100));
// 任何情况下集合的删除与数据的查询都必须提供有 equals 方法
set.remove(new Book("c",89));
System.out.println(set.contains(new Book("c",89)));
System.out.println(set);
Object object [] = set.toArray();
for(int i = 0; i < object.length; i ++){
System.out.println(object[i]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐