简体   繁体   中英

ArrayList and the sort Method of Collections

this method is supposed to iterate on the TreeMaps keys. Then it should add the key to an ArrayList variable because I need to return it as one. One more thing I want to do is to sort the ArrayList.

    ArrayList<String> getVehiclenames() {
         ArrayList<String> vehicleList = new ArrayList<>();
         for (String elem : vehicles.keySet()) {
             vehicleList.add(elem);
         }
    Collections.sort(vehicleList);
    return vehicleList;
}

I am not 100%ly sure wether thats working, but I still couldnt believe anyways that calling a collections method just sort my vehiclelist like that. I expected something like vehicleList = Collections.sort(vehicleList);.

My questions: Is this working like that? And if yes: How is that working? I tried to look it up but my knowledge is to norrow right now.

From the documentation :

This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array.

Colletoions.sort((List list) method of the collection interface sorts based on natural ordering. The dataType of list passed in the sort method must be of type Comparable in other words, it should implement comparable interface.

In your case, you have a list of String. and String class implements the comparable interface.

So to answer your question, yes your code should work fine.

For more information, read about comparator & comparable interface http://docs.oracle.com/javase/7/docs/api/java/util/package-summary.html

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