views:

498

answers:

2

I am new to Java, the function I would like to perform is to load a series of data from a file, into my hashSet() function.

the problem is, I able to enter all the data in sequence, but I can't retrieve it out in sequence base on the account name in the file.

Can anyone help?

below is my code:

public Set retrieveHistory(){ Set dataGroup = new HashSet(); try{

        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());

    }
+1  A: 

java.util.Set is a unique (element may appear only once), non-ordered, hash-based (objects must fulfill the Object.hashCode() contract) collection.

You probably want an ordered collection. LinkedHashSet is a unique, ordered (by insertion order), hash based collection.

Ran Biron
THANKS You so much !! i get it.. =)
vincent low
+2  A: 

Directly from the HashSet class 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.

If you are using this class there is no way to guarantee order. You will need to introduce another data structure in order to do this. Such as ArrayList or LinkedHashSet.

Mimisbrunnr
how about if using hashmap?? thanks for your comment
vincent low
ok i get it d... with using linkedHashSet !! thanks you so much !!
vincent low