我看到了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