Create TreeSet object from one HashSet

1

The code:

    public class FooFoo {

    public static void main(String[] args) {


        Set set = new HashSet<>();
        set.add("hola");
        set.add(2.3);
        set.add(4.2F);
        set.add(1);

        TreeSet set2 = new TreeSet<>(set);
    }
}

The error:

  

Exception in thread "main" java.lang.ClassCastException: java.lang.Float can not be cast to java.lang.Integer at   java.lang.Integer.compareTo (Integer.java:52) at   java.util.TreeMap.put (TreeMap.java:568) at   java.util.TreeSet.add (TreeSet.java:255) at   java.util.AbstractCollection.addAll (AbstractCollection.java:344) at   java.util.TreeSet.addAll (TreeSet.java:312) at   java.util.TreeSet. (TreeSet.java:160) at   foo.FooFoo.main (FooFoo.java:19)

Why it fails, I do not understand.

Thanks in advance

Best regards

    
asked by pelaitas 27.11.2018 в 12:41
source

2 answers

1

A TreeSet unlike a HashSet , matiene ordered its elements.
In order to maintain the ordered elements you have to be able to compare them.

The elements that you are wanting to add are of different types, and that is why you can not compare them.

For example how could we say that "hola" is greater, less or equal to 2.3 ?

Maybe you have an armed logic to establish how the different elements should be compared.

Although I never tried it with elements of different types (I do not mix types in the collections), when you create the TreeSet , you can pass an object Comparator that allows you to program how the elements should be compared with each other.

I imagine that if possible, you would have to use typeof first of all to know what type it is and then apply the corresponding logic.

    
answered by 27.11.2018 в 12:59
0

The problem is that you are actually defining different types within HashSet :

  

Exception in thread "main" java.lang.ClassCastException:   java.lang.Float can not be cast to java.lang.Integer

If the values were of the same type, for example String you could convert from HashSet to TreeSet copying all the elements:

Set set = new HashSet<>();
set.add("hola");
set.add("2.3");
set.add("4.2F");
set.add("1");

//*Convierte a TreeSet
TreeSet<String> set2 = new TreeSet<String>(set);
    
answered by 27.11.2018 в 20:31