0

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

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

任何人都可以帮忙吗?

下面是我的代码:

public Set retrieveHistory(){ Set dataGroup = 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());

    }
4

2 回答 2

3

直接来自HashSet类 javadoc

该类实现了由哈希表(实际上是 HashMap 实例)支持的 Set 接口。它不保证集合的迭代顺序;特别是,它不保证订单会随着时间的推移保持不变。此类允许空元素。

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

于 2010-03-28T18:30:54.853 回答
1

java.util.Set 是一个唯一(元素只能出现一次)、无序、基于哈希(对象必须满足 Object.hashCode() 协定)的集合。

您可能想要一个有序的集合。LinkedHashSet 是一个唯一的、有序的(按插入顺序)、基于散列的集合。

于 2010-03-28T18:28:46.613 回答