Java 自定义对象集包含相同的对象

Java 自定义对象集包含相同的对象,java,set,Java,Set,我看到JavaSet的一些奇怪行为。下面是我遇到问题的非常简单的代码片段: public Set<StopSequence> reduce() { Set<StopSequence> stopSequences = new HashSet<StopSequence>(); StopSequence currentSequence = null; for (StopTime stopTime: mStopTimes) {

我看到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;
}
第二个
系统.out.println的输出,my
集合
仅包含相同的对象。发生了什么事

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

您确定这里给出的代码会产生您给出的输出吗?我之所以这样问,是因为“添加序列:”应该是每次都在自己的行上。而且,代码只创建了一个
StopSequence
对象,所以我不知道它如何生成第一组输出。我建议您编写一个与原始代码分开的程序,它编译并再现您所问的确切问题。请确保将此新程序限制为复制当前问题所需的代码。是的,我刚刚修剪了
\n
以节省一些空间。每次我都会尝试创建一个新的停止序列,看看是否有效。但是我为什么要得到这个输出呢?是的,我仍然很好奇为什么我首先得到了这个输出……在你的原始代码中,调用
stopSequence.add()
只是一遍又一遍地将同一个对象添加到
列表中……那么为什么我在“Added sequence”语句中得到不同的加法呢?
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