【问题标题】:HashSet Output not matching [JAVA]HashSet 输出不匹配 [JAVA]
【发布时间】:2016-08-22 10:29:45
【问题描述】:

代码是从文件中读取并生成一个HashSet然后输出到控制台。

我的代码输出和预期的输出不匹配。

我的java代码是

Main.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader brf = new BufferedReader(new FileReader("calllog.txt"));


        Set<String> phoneNumberList = new HashSet<String>();


        String read = "";
        while ((read = brf.readLine()) != null) {

            String[] callList = read.split(",");


            String in = callList[0];
            phoneNumberList.add(in);     //add(new CallLog(callList[0], startTime, endTime));


        }
        brf.close();

        Iterator<String> itr = phoneNumberList.iterator();

        while(itr.hasNext()){
            System.out.println(itr.next());
        }


    }

}

calllog.txt

8123456789,10-10-2015 10:00:00,10-10-2015 10:28:59
8123456789,11-10-2015 11:00:00,10-10-2015 11:51:00
8123456789,12-10-2015 12:00:00,10-10-2015 12:10:35
9123456789,11-10-2015 11:00:00,11-10-2015 11:32:43
0422-201430,12-10-2015 12:00:00,12-10-2015 11:05:16
0422-201430,12-10-2015 12:06:00,12-10-2015 11:10:20
9764318520,13-10-2015 13:00:00,13-10-2015 10:10:15
0422-201430,12-10-2015 12:00:00,12-10-2015 12:05:16
0422-201430,13-10-2015 14:05:00,13-10-2015 14:15:00
0422-201430,15-10-2015 16:08:00,15-10-2015 16:35:57

我的输出

9123456789
9764318520
0422-201430
8123456789

预期输出

8123456789
9764318520
0422-201430
9123456789

【问题讨论】:

    标签: java collections hashset


    【解决方案1】:

    HashSet 没有排序,因此您没有理由期望元素的特定排序。

    如果您希望根据插入顺序对元素进行排序,您可以使用LinkedHashSet,但这会给您

    8123456789
    9123456789
    0422-201430
    9764318520
    

    这不是您的预期顺序。

    【讨论】:

    • 是输出系统依赖还是jdk依赖?
    • @AnkushSingh 在不同的JDK版本中可能会有所不同,因为它取决于HashMap / HashSet的内部实现。
    • 它不仅依赖于 JDK,还依​​赖于 HashSets 的内部状态。考虑this demo,它表明相同的元素可以有不同的顺序。
    • @andy 我可以通过实现我自己的 hashcode() 来更改输出顺序吗?只是想知道
    • @Ankush 实现哈希码不会使订单变得不那么不确定。它可能会改变观察到的迭代顺序,但不会以有意义或可靠的方式改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2018-05-10
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多