Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is collections.sort method only used for List type of collections?

friends, I am new to Java-Collection. I want to ask does Collections.sort() method only used for/by collections which are List type. I was unable to sort following code:

Collection collection=new HashSet();
collection.add("zebra");
collection.add("frog");
collection.add("bison");
collection.add("puma");
Collections.sort(collection); //error...why??

I know that HashSet is used for unique elements. But is there any way to sort this collection?

like image 395
JPG Avatar asked Dec 01 '22 01:12

JPG


2 Answers

Collections.sort method expects a collection that implements a List<T> interface. This makes sense, because lists have a defined sequence. In other words, your program has complete control of the order of what goes in the list.

Unlike lists, sets are either unordered, or specify their own, specific ordering. That is why trying to sort a Set does not make sense: it is the set, not your program, that defines the ordering of the items in the set collection. Your program can provide the logic to customize that ordering, but you cannot take an existing set, and force a different order on its items from the outside.

If you would like to get all items of a set collection in a sorted order, copy your set into an array list, and sort the results.

like image 50
Sergey Kalinichenko Avatar answered Dec 04 '22 12:12

Sergey Kalinichenko


The error is because the Collections class only supports a List.

public static <T extends Comparable<? super T>> void sort(List<T> list)

To sort your collection, you can try something like:

Collection collection=new HashSet();
collection.add("zebra");
collection.add("frog");
collection.add("bison");
collection.add("puma");
ArrayList<String> temp = new ArrayList<String>(collection);
Collections.sort(temp);
collection = new HashSet(temp);

Hope this helps.

like image 43
Ayman Avatar answered Dec 04 '22 10:12

Ayman