HashSet与TreeSet都实现了Set接口,但是它们有一些小区别:
看个程序先:
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
public class SetTest
{
public static void main(String[] args)
{
HashSet<String> set = new HashSet<String>();
set.add("a");
set.add("b");
set.add("c");
set.add("b");
String s = new String("e");
String s1 = new String("e");
set.add(s1);
set.add(s);
System.out.println(set);
SetTest test = new SetTest();
SetTest test1 = new SetTest();
System.out.println(test.hashCode());
System.out.println(test1.hashCode());
Iterator<String> iter = set.iterator();
while(iter.hasNext())
{
String value = (String) iter.next();
System.out.print(value+",");
}
TreeSet<String> tree = new TreeSet<String>();
tree.add("D");
tree.add("A");
tree.add("C");
tree.add("E");
System.out.println("
"+tree);
}
}
程序运行结果如下:
[e, b, c, a]
31275026
9192299
e,b,c,a,
[A, C, D, E]
可以看出,实现了Set接口的HashSet和TreeSet它们对于字符串都不会允许有重复的值存在(不同于实现了List接口的那些类,如:ArrayList,LinkedList),即使这些字符串的引用不同,换句话说,不允许有具有相同HashCode的对象存在于HashSet或TreeSet中。那么对于Object类型的参数来说,字符串的这种判断方式并不适用,即使这些Object类型中所有的变量值和变量类型都一样,如果,真的要忽视引用地址的不同,那么可以重写equeals方法和hashCode方法,但是API不推荐我们修改equeals方法。不同的是HashSet中的值存放不是定序的,而TreeSet中的值是有序的。
另外一个程序:
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeSet;
public class CompareTest
{
public static void main(String[] args)
{
TreeSet<Person> set = new TreeSet<Person>( new MyCompare());
set.add(new Person('C'));
set.add(new Person('a'));
set.add(new Person('A'));
set.add(new Person('B'));
set.add(new Person('E'));
set.add(new Person('f'));
System.out.println(set);
for(Iterator< Person> iter = set.iterator();iter.hasNext();)
{
String value = iter.next().toString();
System.out.println(value);
}
LinkedList<Integer> link = new LinkedList<Integer>();
link.add(new Integer(5));
link.add(new Integer(-5));
link.add(new Integer(-15));
link.add(new Integer(15));
Comparator< Integer> c = Collections.reverseOrder();//反序方式
Collections.sort(link,c);
for(Iterator< Integer> iter = link.iterator();iter.hasNext();)
{
System.out.print(iter.next()+" .. ");
}
Collections.shuffle(link);//乱序
for(Iterator< Integer> iter = link.iterator();iter.hasNext();)
{
System.out.print(iter.next()+"/");
}
System.out.println("
max:"+Collections.max(link));
System.out.println("min:"+Collections.min(link));
}
}
class MyCompare implements Comparator<Object>
{
public int compare(Object o1, Object o2)
{
String obj1 = o1.toString();
String obj2 = o2.toString();
return obj2.compareTo(obj1);
}
}
class Person
{
char name;
public Person(char name)
{
this.name = name;
}
public String toString()
{
return String.valueOf(this.name);
}
}
运行结果如下:
[f, a, E, C, B, A]
f
a
E
C
B
A
15 .. 5 .. -5 .. -15 .. 5/15/-15/-5/
max:15
min:-15