Java Set( 不允许重复的集合)

HashSet:  防止重复
使用HashSet的class必须implements Comparable();
ArrayList<class> classList=new ArrayList<class>();
HashSet<class> classSet=new HashSet<class>();
classSet.addAll(classList);     //addAll()可以复制其他集合的元素,效果就跟一个一个加进去一样


但是仅仅这样做的话还是会有重复;
HashSet如何检查重复? :hashCode()和equals():     //相同的对象必须hashCode()相同并且equals()返回true,但hashCode()相同的对象不一定相同。
必须覆盖hashCode()和equals():   hashCode()的默认行为是对在heap上的对象产生独特的值,如果没有override过hashCode(),则该class的两个对象怎样都不会被认为是相同的。
class class implements Comparable<class>{
String title;
public boolean equals (Object a){
     class s=(class)a;
     return title.equals(a.getTitle());
}
public int hashCode(){
return title.hashCode();
}
}



TreeSet:防止重复并保持有序
TreeSet<Class> classSet=new TreeSet<Class>();  //调用没有参数的构造函数来用TreeSet取代HashSet意味着以对象的compareTo()方法来进行排序
classSet.addAll(classList);
要使用TreeSet,下列一项必须为真:
*集合中的元素必须是有实现Comparable的类型,并覆盖了compareTo(Object o)方法。例如:
class Book implements Comparable{
String title;
public int compareTo(Object b)
{Book book=(Book)b;  return title.compareTo(book.title);}}


或*使用重载、取用Comparator参数的构造函数来创建TreeSet。例如:
class BookCompare implements  Comparator<Book>{
public int compare(Book one,Booke two)
{return one.title.compareTo(two.title);}}
class Test{
BookCompare bCompare=new BookCompare();
TreeSet<Book> tree=new TreeSet<Book>(bCompare);}


猜你喜欢

转载自blog.csdn.net/qq_34999633/article/details/79502792