我正在检查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 tree = new TreeSet();
tree.add(s1);
tree.add(s2);
tree.add(s3);
tree.add(s4);
System.out.println(tree);
}
}
class Song implements Comparable{
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类默认实现?看起来它使用“标题”字段进行此检查,因为当我添加时将其视为重复但是当我添加它时不会将其视为重复.
谢谢.