TreeMap and SortedMap conversion statement

605 views Asked by At

What is wrong with this statement?

private final HashMap<String, SortedMap<Long, Long>> abc;
abc = new HashMap<String, TreeMap<Long, Long>>;

It shows the error that SortedMap cannot be converted to TreeMap like this? How do I make this possible?

2

There are 2 answers

0
flakes On

If you really want to be able to assign it this way, then can you use a wildcard with bound ? extends SortedMap. eg:

private final Map<String, ? extends SortedMap<Long, Long>> abc;
...
abc = new HashMap<String, TreeMap<Long, Long>>();

That said, you don't have to specify the nested map type when you create the new outer hashmap instance.. just keep it as a SortedMap. Later when you insert a value it can be new TreeMap instances because they implement SortedMap. eg

private final Map<String, SortedMap<Long, Long>> abc;
...
abc = new HashMap<String, SortedMap<Long, Long>>();
abc.put("Test", new TreeMap<Long, Long>());

After shortening this code for type inference, the assignment lines could look like bellow:

abc = new HashMap<>();
abc.put("Test", new TreeMap<>());
0
jack jay On

You haven't initialized your HashMap. Remember to use constructor when you are instantiating new object.

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
        HashMap<String,SortedMap<Long,Long>> abc;
        abc = new HashMap<>();
    }
}