tags:

views:

134

answers:

5

Original code without the cast:

ArrayList<String> elements = new ArrayList<String>();
for (ListTreeNode pos : positions)
    elements.add(pos.getElement());

In ListTreeNode:

public String getElement() {
    return element;
}

Eclipse is telling me that it is an unchecked cast from String to String if I do:

elements.add((String)pos.getElement());

I put the cast in there because before that it was telling me that the method add(String) in the ArrayList is not applicable for the type (String). I don't get that?

A: 
public class ListTree<String> {

That was the answer.

To clarify, I removed the generic type specifier. That was causing the problem. The code now looks like:

public class ListTree {
BobTurbo
How does that fix the problem?
TheLQ
That wouldn't even compile.
The Alchemist
+2  A: 

Eclipse thinks there are two different String types. One could for example have a com.example.String. If both are java.lang.String and Eclipse somehow makes a distinction, there's very interesting.

irreputable
Wouldn't eclipse complain because both types are incompatible. `java.lang.String` is final, so `com.example.String` can not extend `java.lang.String` neither the other way around.
Willi
good point, such casts should cause compile error. if neither are java.lang.String, then it is possible.
irreputable
+1  A: 

Are they both java.lang.String? That is only way eclipse will complain. If not, clean the project and see if it works.

fastcodejava
A: 

Check you Eclipse project for multiple inclusions of the JVM libraries. An example that would cause what you see is two projects, A and B, where B uses A and the JVM settings for B is different than the JVM settings for A. The String class that A uses B is not the same String class that B uses. Check your launcher settings as well.

Faron
A: 

Just an IT answer :

Have you tried to turn it off and on ?

I know it seems stupid but sometimes eclipse gets "tired" and throws errors even if your code works perfectly.

Colin Hebert