JohnJohnGa
JohnJohnGa

Reputation: 15685

TreeMap generic argument warning

Map<Date, Integer> m = new HashMap<Date, Integer>(); // line 1
Map<Date, Integer> sMap = new TreeMap(m);            // line 2

Line 2 gives this error:

Type safety: The expression of type TreeMap needs unchecked conversion to conform to Map

The solution I found is this: How do I fix "The expression of type List needs unchecked conversion...'?

But, is it safe to simply @SuppressWarnings("unchecked") or is there a scenario when my code will failed. More generally, when can we safely add the @SuppressWarnings("unchecked")?

Upvotes: 1

Views: 1519

Answers (4)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Try specifying the generic types of the TreeMap when you instantiate it.

Map<Date, Integer> m = new HashMap<Date, Integer>(); // line 1
Map<Date, Integer> sMap = new TreeMap<Date,Integer>(m);

This answer assumes you are using java.util.TreeMap. See: http://docs.oracle.com/javase/7/docs/api/

Upvotes: 4

user647772
user647772

Reputation:

If you use Java 7, you can use the diamond syntax:

Map<Date, Integer> m = new HashMap<>();
Map<Date, Integer> sMap = new TreeMap<>(m);

Upvotes: 2

Pyranja
Pyranja

Reputation: 3589

As already said, adding generic parameters to the TreeMap resolves the problem, as the compiler can now guarantee that no invalid casts will happen. If you omit the generic parameters the compiler cannot give you this guarantee and therefore warns you. Then it is your responsibility that only objects of the correct type are stored in the TreeMap.

If you are you sure that only the correct objects are put into the TreeMap you can safely ignore the warning. If it fails and you encounter class cast exceptions on runtime, it is your own fault (:

Generally speaking if you supress a warning you are effectively ignoring a hint of the compiler that there may be a problem in your code. But the compiler is dumb and there are situations where you can safely say that no problems will occur (e.g. you have other checks in place or a design that does not permit the errors to happen). If that is the case you can suppress the warning.

Upvotes: 0

Stephan
Stephan

Reputation: 4443

The correct way is:

1. Map<Date, Integer> m = new HashMap<Date, Integer>();
2. Map<Date, Integer> sMap = new TreeMap<Date, Integer>(m);

You can also supress the "unchecked" warnings if you are sure about the generic type. In this case, you are.

Upvotes: 1

Related Questions