代码是从文件中读取并生成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
HashSet
是无序的,因此您没有理由期望元素有一定的顺序。
如果你想让元素按照插入顺序排列,你可以使用LinkedHashSet
,但这会给你
8123456789
9123456789
0422-201430
9764318520
不是您期望的顺序