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 インターフェイスを実装します。セットの反復順序については保証されません。特に、順序が長期的に一定であることを保証するものではありません。このクラスは null 要素を許可します。

このクラスを使用している場合、順序を保証する方法はありません。これを行うには、別のデータ構造を導入する必要があります。ArrayListやLinkedHashSetなど

于 2010-03-28T18:30:54.853 に答える
1

java.util.Set は、一意の (要素は 1 回だけ出現する可能性がある)、順序付けされていないハッシュベースの (オブジェクトは Object.hashCode() 契約を満たす必要がある) コレクションです。

おそらく、順序付けられたコレクションが必要です。LinkedHashSet は、(挿入順で) 順序付けされた一意のハッシュ ベースのコレクションです。

于 2010-03-28T18:28:46.613 に答える