我檢查如何TreeSet的檢查重複的元素,並具有以下代碼如何TreeSet的檢查重複
import java.util.*;
public class TreeDemo{
public static void main(String[] args)
{
new TreeDemo().go();
}
public void go()
{
Song s1 = new Song("song1","artist1");
Song s2 = new Song("song2","artist2");
Song s3 = new Song("song3","artist3");
Song s4 = new Song("song3","artist3");
Set<Song> tree = new TreeSet<Song>();
tree.add(s1);
tree.add(s2);
tree.add(s3);
tree.add(s4);
System.out.println(tree);
}
}
class Song implements Comparable<Song>{
private String title;
private String artist;
public Song(String t, String a)
{
title=t;
artist=a;
}
public String getTitle(){
return title;
}
public int compareTo(Song s){
//Song s = (Song)o;
return title.compareTo(s.getTitle());
}
public String toString(){
return title;
}
}
當我執行這個代碼,我得到以下輸出
[song1, song2, song3]
我的問題是: -
- 即使我沒有實現hashCode和equals方法(我沒有實現Comparable接口,因爲它的強制並需要保持Set排序),TreeSet是如何確定重複的?
- 它使用了Object類的默認實現嗎?它看起來像它使用「標題」字段進行此檢查,因爲當我添加將它視爲重複,但是當我添加它不會將其視爲重複。
謝謝。
從Comparable接口文檔中,它表示:「強烈建議...自然排序與平等一致。」 – newacct 2012-04-11 05:10:47