gpt4 book ai didi

java - 如何对HashSet()函数数据按顺序排序?

转载 作者:行者123 更新时间:2023-12-01 19:23:50 26 4
gpt4 key购买 nike

我是 Java 新手,我想要执行的功能是将文件中的一系列数据加载到我的 hashSet() 函数中。

问题是,我可以按顺序输入所有数据,但无法根据文件中的帐户名按顺序检索出来。

有人可以帮忙吗?

下面是我的代码:

公共(public)设置检索历史记录(){ 设置数据组 = new HashSet(); 尝试{

        File file = new File("C:\\Documents and Settings\\vincent\\My Documents\\NetBeansProjects\\vincenttesting\\src\\vincenttesting\\vincenthistory.txt");

BufferedReader br = new BufferedReader(new FileReader(file));
String data = br.readLine();
while(data != null){
System.out.println("This is all the record:"+data);
Customer cust = new Customer();
//break the data based on the ,
String array[] = data.split(",");
cust.setCustomerName(array[0]);
cust.setpassword(array[1]);
cust.setlocation(array[2]);
cust.setday(array[3]);
cust.setmonth(array[4]);
cust.setyear(array[5]);
cust.setAmount(Double.parseDouble(array[6]));
cust.settransaction(Double.parseDouble(array[7]));
dataGroup.add(cust);
//then proced to read next customer.

data = br.readLine();
}
br.close();
}catch(Exception e){
System.out.println("error" +e);
}
return dataGroup;
}

public static void main(String[] args) {
FileReadDataModel fr = new FileReadDataModel();
Set customerGroup = fr.retrieveHistory();
System.out.println(e);
for(Object obj : customerGroup){
Customer cust = (Customer)obj;

System.out.println("Cust name :" +cust.getCustomerName());
System.out.println("Cust amount :" +cust.getAmount());

}

最佳答案

直接来自HashSet javadoc 类

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

如果您使用此类,则无法保证顺序。为此,您将需要引入另一种数据结构。如ArrayListLinkedHashSet .

关于java - 如何对HashSet()函数数据按顺序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2533993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com