java.util
子接口 set<E>
特點:
Set:無序的,無索引,元素不可重複
Set集合的功能和Collection是一致的,一個不包含重複元素的 collection
|--Set:元素是無序(存入和取出的順序不一定一致),元素不可以重複。、
|--HashSet:底層數據結構是哈希表。是線程不安全的。不同步。!無序的
HashSet是如何保證元素唯一性的呢?
是通過元素的兩個方法,hashCode和equals來完成。
如果元素的HashCode值相同,纔會判斷equals是否爲true。
如果元素的hashcode值不同,不會調用equals。
注意,對於判斷元素是否存在,以及刪除等操作,依賴的方法是元素的hashcode和equals方法。
|--TreeSet:可以對Set集合中的元素進行排序。!有自然排序的功能
底層數據結構是二叉樹。
保證元素唯一性的依據:
compareTo方法return 0.
TreeSet排序的第一種方式:讓元素自身具備比較性。
元素需要實現Comparable接口,覆蓋compareTo方法。
也種方式也成爲元素的自然順序,或者叫做默認順序。
java.lang
接口 Comparable<T>
TreeSet的第二種排序方式。
當元素自身不具備比較性時,或者具備的比較性不是所需要的。
這時就需要讓集合自身具備比較性。
在集合初始化時,就有了比較方式
定義了比較器,
將比較器對象作爲參數傳遞給TreeSet集合的構造函數。
當兩種排序都存在時,以比較器爲主。
定義一個類,實現Comparator接口,覆蓋compare方法
ava.util
接口 Comparator<T>
hashSet集合中存入自定對象
姓名和年齡相同爲同一個人,重複元素(覆蓋equals,hashcode方法)
public int hashCode()
{
System. out.println(this.name +"....hashCode" );
return name.hashCode()+ age*37;
}
public boolean equals(Object
obj)
{
if(!(obj instanceof Person))
return false ;
Person p = (Person )obj;
System.out.println( this.name+ "...equals.."+p.name);
return this .name.equals(p.name)
&& this.age ==
p.age;
}
TreeSet集合中存入自定對象使之具備比較性方便排序
TreeSet排序的第一種方式:讓元素自身具備比較性。
class Student implements Comparable//
該接口強制讓學生具備比較性。
{
private String name ;
private int age ;
Student(String name, int age)
{
this.name =
name;
this.age =
age;
}
public int compareTo(Object
obj) {
// return 0;
if (!(obj instanceof Student))
throw new RuntimeException("不是學生對象");
Student s = (Student) obj;
System. out.println(this.name + "....compareto....." +
s.name);
if (this .age >
s.age)
return 1;
if (this .age ==
s.age) {
return this .name .compareTo(s.name);
}
return -1;
/**/
}
}
TreeSet的第二種排序方式。讓集合自身具備比較性。
TreeSet tr = new TreeSet(new MyCompare());
class MyCompare implements Comparator
{
public int compare (Object
o1,Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int num
= s1.getName().compareTo(s2. getName());
if(num==0)
{
return new Integer(s1.getAge ()).compareTo(new Integer(s2.getAge()));
/*
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()==s2.getAge())
return 0;
return -1;
*/
}
return num;
}
}