HashSet
此類(lèi)實(shí)現(xiàn) Set 接口,由哈希表(實(shí)際上是一個(gè) HashMap 實(shí)例)支持。它不保證集合的迭代順序;特別是它不保證該順序恒久不變。此類(lèi)允許使用 null 元素。
此類(lèi)為基本操作提供了穩(wěn)定性能,這些基本操作包括 add、remove、contains 和 size,假定哈希函數(shù)將這些元素正確地分布在桶中。對(duì)此集合進(jìn)行迭代所需的時(shí)間與 HashSet 實(shí)例的大?。ㄔ氐臄?shù)量)和底層 HashMap 實(shí)例(桶的數(shù)量)的“容量”的和成比例。因此,如果迭代性能很重要,則不要將初始容量設(shè)置得太高(或?qū)⒓虞d因子設(shè)置得太低)。
我們應(yīng)該為要存放到散列表的各個(gè)對(duì)象定義hashCode()和equals();
import java.util.HashSet;
import java.util.Iterator;
public class HashSetTest {
public static void main(String[] args)
{
HashSet hs=new HashSet();
/*hs.add("one");
hs.add("two");
hs.add("three");
hs.add("four");*/
hs.add(new Student(1,"zhangsan"));
hs.add(new Student(2,"lishi"));
hs.add(new Student(3,"wangwu"));
hs.add(new Student(1,"zhangsan"));
Iterator it=hs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
//HashSet要重寫(xiě)hashCode和equals方法
class Student
{
int num;
String name;
Student(int num,String name)
{
this.num=num;
this.name=name;
}
public String toString()
{
return "num :"+num+" name:"+name;
}
public int hashCode()
{
return num*name.hashCode();
}
public boolean equals(Object o)
{
Student s=(Student)o;
return num==s.num && name.equals(s.name);
}
}
TreeSet
此類(lèi)實(shí)現(xiàn) Set 接口,該接口由 TreeMap 實(shí)例支持。此類(lèi)保證排序后的 set 按照升序排列元素,根據(jù)使用的構(gòu)造方法不同,可能會(huì)按照元素的自然順序 進(jìn)行排序,或按照在創(chuàng)建 set 時(shí)所提供的比較器進(jìn)行排序。
是一個(gè)有序集合,元素中安升序排序,缺省是按照自然順序進(jìn)行排序,意味著TreeSet中元素要實(shí)現(xiàn)Comparable接口;
我們可以構(gòu)造TreeSet對(duì)象時(shí),傳遞實(shí)現(xiàn)了Comparator接口的比較器對(duì)象.
import java.util.*;
public class TreeSetTest {
public static void main(String[] args)
{
//TreeSet ts=new TreeSet();
TreeSet ts=new TreeSet(new Students.compareToStudent());
ts.add(new Students(2,"zhangshan"));
ts.add(new Students(3,"lishi"));
ts.add(new Students(1,"wangwu"));
ts.add(new Students(4,"maliu"));
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class Students implements Comparable
{
int num;
String name;
Students(int num,String name)
{
this.num=num;
this.name=name;
}
//定義一個(gè)內(nèi)部類(lèi)來(lái)實(shí)現(xiàn)比較器
static class compareToStudent implements Comparator
{
public int compare(Object o1, Object o2) {
Students s1=(Students)o1;
Students s2=(Students)o2;
int rulst= s1.num > s2.num ? 1 : (s1.num==s2.num ? 0 :-1);
if(rulst==0)
{
rulst=s1.name.compareTo(s2.name);
}
return rulst;
}
}
//寫(xiě)具體的比較方法
public int compareTo(Object o)
{
int result;
Students s=(Students)o;
result=num >s.num ? 1:(num==s.num ? 0 : -1);
if(result==0)
{
result=name.compareTo(s.name);
}
return result;
}
public String toString()
{
return num+":"+name;
}
}
HashSet是基于Hash算法實(shí)現(xiàn)的,其性能通常優(yōu)于TreeSet,我們通常都應(yīng)該使用HashSet,在我們需要排序的功能時(shí),我門(mén)才使用TreeSet;
說(shuō)了這么多廢話就是一點(diǎn)compareTo這個(gè)方法,當(dāng)?shù)扔诘臅r(shí)候就返回0,當(dāng)大于就返回1,當(dāng)小于就返回-1,別發(fā)呆,就這么簡(jiǎn)單,有幫你排一排和亂亂的而已;
柴油發(fā)電機(jī)
發(fā)電機(jī)
柴油機(jī)
柴油發(fā)電機(jī)
13636374743(上海)
13291526067(嘉興)