您的位置:首页 > 其它

示例比较HashSet,LinkedHashSet,TreeSet

2013-07-19 01:37 357 查看
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;

public class T01{

private static class Ob implements Comparable<Ob>{
private int idx = 0;

public Ob(int idx){
this.idx = idx;
}

public int getIdx(){
return idx;
}

public void setIdx(int idx){
this.idx = idx;
}

@Override
public int hashCode(){
final int prime = 31;
int result = 1;
result = prime * result + idx;
return result;
}

@Override
public boolean equals(Object obj){
if(this == obj) return true;
if(obj == null) return false;
if(getClass() != obj.getClass()) return false;
Ob other = (Ob)obj;
if(idx != other.idx) return false;
return true;
}

@Override
public int compareTo(Ob o){
return o.getIdx();
}

@Override
public String toString(){
return "Ob[" + idx + "]";
}

}

/**
*
* @param args void
*/
public static void main(String[] args){
//treeset 有序去重,内部是二叉树实现,string默认实现了java.lang.Comparable接口
TreeSet s = new TreeSet();
s.add("b");
s.add("ab");
s.add("a");
s.add("c");
s.add("c");
s.add("c");
s.add("d");
s.add("e");
System.out.println("s: "+s);

//linkedhashset 有序去重,内部hash
LinkedHashSet<Integer> d = new LinkedHashSet<Integer>();
d.add(1);
d.add(3);
d.add(2);
d.add(2);
d.add(2);
d.add(4);
d.add(5);
System.out.println("d: "+d);

//treeset 内部对象要求实现java.lang.Comparable接口
TreeSet k = new TreeSet();
k.add(new Ob(1));
k.add(new Ob(3));
k.add(new Ob(5));
k.add(new Ob(4));
k.add(new Ob(2));
k.add(new Ob(2));
k.add(new Ob(2));
k.add(new Ob(6));
System.out.println("k: "+k);

//HashSet 无序去重,内部hash
HashSet x = new HashSet();
x.add(new Ob(1));
x.add(new Ob(3));
x.add(new Ob(5));
x.add(new Ob(4));
x.add(new Ob(2));
x.add(new Ob(6));
System.out.println("x: "+x);

//LinkedHashSet 有序去重,内部hash
LinkedHashSet x1 = new LinkedHashSet();
x1.add(new Ob(1));
x1.add(new Ob(3));
x1.add(new Ob(5));
x1.add(new Ob(4));
x1.add(new Ob(2));
x1.add(new Ob(6));
System.out.println("x1: "+x1);

//HashSet 加数字,默认按数字排序
HashSet y = new HashSet();
y.add(2);
y.add(1);
y.add(4);
y.add(3);
y.add(5);
y.add(5);
y.add(6);
System.out.println("y: "+y);

//HashSet 加对象,无序去重
HashSet z = new HashSet();
z.add("a");
z.add("c");
z.add("b");
z.add("b");
z.add("e");
z.add("e");
z.add("e");
z.add("d");
z.add("f");
System.out.println("z: "+z);

//LinkedHashSet 加对象,有序去重
LinkedHashSet o = new LinkedHashSet();
o.add("a");
o.add("c");
o.add("b");
o.add("b");
o.add("e");
o.add("e");
o.add("e");
o.add("f");
o.add("d");
System.out.println("o: "+o);

//		运行结果:
//		s: [a, ab, b, c, d, e]
//		d: [1, 3, 2, 4, 5]
//		k: [Ob[1], Ob[3], Ob[5], Ob[4], Ob[2], Ob[2], Ob[2], Ob[6]]
//		x: [Ob[3], Ob[4], Ob[1], Ob[2], Ob[5], Ob[6]]
//		x1: [Ob[1], Ob[3], Ob[5], Ob[4], Ob[2], Ob[6]]
//		y: [1, 2, 3, 4, 5, 6]
//		z: [f, d, e, b, c, a]
//		o: [a, c, b, e, f, d]

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: