有一个需求是这样的,要求去掉重复Id的文章,如果id相同就去掉,如果不同就按文章发表时间排序,但写完代码发现,id相同的文章怎么也去重不了:
[code="java"]
public class ArticleSource implements Comparable {
private long id;
private int sourceId;
private long time;
public ArticleSource(long id,int sourceId,long time) {
this.id = id;
this.sourceId = sourceId;
this.time = time;;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getSourceId() {
return sourceId;
}
public void setSourceId(int sourceId) {
this.sourceId = sourceId;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
@Override
public boolean equals(Object obj) {
System.out.println("equals");
if(obj instanceof ArticleSource) {
ArticleSource at = (ArticleSource)obj;
if(at.getId() == this.getId()) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
System.out.println("hash");
return (int) id;
}
@Override
public int compareTo(ArticleSource o) {
if(o == null) {
return 0;
}
System.out.println(o.getId() + "=>"+this.getId() );
if(o.getId() == this.getId()) {
return 0;
}
if(o.getTime() >this.getTime()) {
return -1;
}else if(o.getTime()==this.getTime()){
return 0;
}else {
return 1;
}
}
@Override
public String toString() {
return id +":" + time;
}
public static void main(String[] args) {
Set<ArticleSource> set = new TreeSet<ArticleSource>();
set.add(new ArticleSource(391454L, 1420, 13626506898983L));
set.add(new ArticleSource(3914064L, 1420, 10000L));
set.add(new ArticleSource(3914065L, 4235, 1362650633576L));
set.add(new ArticleSource(3914064L, 4235, 1363333333333L));
System.out.println(set);
}
[/code]
结果:
[code="java"]
391454=>3914064
391454=>3914065
3914064=>3914065
3914065=>3914064
391454=>3914064
[3914064:10000, 3914065:1362650633576, 3914064:1363333333333, 391454:13626506898983]
[/code]
诡异的是,第二个和第四个id是相同的,竟然无法去重,更诡异的是,把第四个的time 少一位,就是136333333333L,又可以去掉重复,请教一下,是什么原因?难道long不允许超过13位吗
结果:
[code="java"]
391454=>3914064
391454=>3914065
3914064=>3914065
3914065=>3914064
3914064=>3914064
[3914064:10000, 3914065:1362650633576, 391454:13626506898983]
[/code]