我看到 Java 的一些奇怪行为Set
。这是我遇到问题的非常简单的代码片段:
public Set<StopSequence> reduce() {
Set<StopSequence> stopSequences = new HashSet<StopSequence>();
StopSequence currentSequence = null;
for (StopTime stopTime: mStopTimes) {
if (stopTime.getStopSequence() == 0) {
//beginning of a new sequence
if (currentSequence != null) {
if (stopSequences.add(currentSequence)) {
System.out.println("Added sequence:");
System.out.println(currentSequence.toString());
}
currentSequence.clear();
} else {
currentSequence = new StopSequence();
}
currentSequence.add(stopTime.getStopId());
} else {
currentSequence.add(stopTime.getStopId());
}
}
Iterator<StopSequence> iterator = stopSequences.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
return stopSequences;
}
现在看看控制台输出,你会发现问题:
第一个的输出System.out.println
,一切似乎都很好:
Added sequence: com.bviproject.gtfsobjects.StopSequence@d48dbbe6
Added sequence: com.bviproject.gtfsobjects.StopSequence@d5e1c8a1
Added sequence: com.bviproject.gtfsobjects.StopSequence@c98eb21
Added sequence: com.bviproject.gtfsobjects.StopSequence@79baf504
Added sequence: com.bviproject.gtfsobjects.StopSequence@6617f5f6
Added sequence: com.bviproject.gtfsobjects.StopSequence@7d7554ff
第二个的输出System.out.println
,我Set
只包含相同的对象。怎么了??
com.bviproject.gtfsobjects.StopSequence@dd017ba7
com.bviproject.gtfsobjects.StopSequence@dd017ba7
com.bviproject.gtfsobjects.StopSequence@dd017ba7
com.bviproject.gtfsobjects.StopSequence@dd017ba7
com.bviproject.gtfsobjects.StopSequence@dd017ba7
com.bviproject.gtfsobjects.StopSequence@dd017ba7
com.bviproject.gtfsobjects.StopSequence@dd017ba7
com.bviproject.gtfsobjects.StopSequence@dd017ba7