Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
937 views
in Technique[技术] by (71.8m points)

java - Type safety: The method.. belongs to the raw type.. refs to generics should be parameterized

Eclipse gives me the warning (in the title) using just the following code in a working project with nothing in it but a dummy class and a main method:

List a = new ArrayList();
List<Integer> b = new ArrayList<Integer>();
int x = 19;
a.add(x);

The last line triggers the warning. I'm not sure what I am doing wrong here, or really, what I am even doing. I am a Java student following a dubious tutorial and I am attempting to understand generics. Supposedly, variable x doesn't illustrate type safety. I tried casting it to the Object type (which I think does nothing because it already is) and it didn't work.

How might I resolve this warning?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have declared List a without the type parameter. This is why eclipse is complaining about type safety, as you could add objects of any type to that list.

If you look at the ArrayList api and take a look at the class declaration, you see it is declared like this:

public class ArrayList<E>

Substitute E with any class you wish.

With List<Integer> b you have explicitly told the compiler that the list is to hold instances of Integer objects only, and the compiler can verify this, thus giving you type safety.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...