简体   繁体   中英

How to sort HashSet() function data in sequence?

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

    }

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM