warning when adding to a list

Hello.
Eclipse gives me this warining when I add something to ArrayList or HashSet with .add() … everything works fine, but I don’t really understand the warning. Please someone explain, thank you.

Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic
type ArrayList should be parameterized

(Excuse my C++ background, I’m sure Java calls these things by different names… but anyway…)

With the latest release, Java now supports a concept similar to C++ templates. One big win with this is the ability to avoid creating classes that have no type safety, like generic collection classes. The warning you are getting is telling you that you are using one of these generic collection classes, when you should be creating a collection to hold the exact type of thing you want in the collection.

So:

ArrayList fishList = new ArrayList;

fishList.add(new CFish(“Salmon”)); // is good.
fishList.add(new CBird(“Hawk”)); // won’t compile

Yup except that it will compile, but with warnings.

The solution is, if your putting objects of type String in the list rather then saying


List stringList = new ArrayList()
stringList.add("mystring");

you say


List<String> stringList = new ArrayList<String>()
stringList.add("mystring");

If you want a list that can take anything you use a wildcard.


List<?> stringList = new ArrayList<?>()
stringList.add("mystring");

that’s a cool feature, I like it 8)
is ArrayList<?> identical to ArrayList or wildcard has some stuff hidden underneath the hood? Also, is this only wildcard or can I use combo with constants, like “?List” ?
tnx ppl.

This page should give you most of the generics info you could want.

http://mindprod.com/jgloss/generics.html

<?> and are not quite the same. Theres an esoteric difference thatI can never remember. Look at one of the many references on generics.

Tehre are actually 2 other forms of the wildcard, <? extends Foo> and <? super Foo>