Viv.java uses unchecked or unsafe operations - explanation and cure
Archive - Originally posted on "The Horse's Mouth" - 2009-09-24 06:47:32 - Graham EllisAre you getting Java compiler messages like this?
Dorothy-2:java grahamellis$ javac Viv.java
Note: Viv.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Dorothy-2:java grahamellis$ javac -Xlint Viv.java
Which when you expand the warning with -Xlint gives:
Dorothy-2:java grahamellis$ javac -Xlint Viv.java
Viv.java:20: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList
trowbridge.add(new Rolf("First Great Western",75,3,60));
^
If so, let me explain.
Java's collection classes - such as ArrayLists and Vectors - can hold any type of object, and the mechanisms of the base Java language allow yo to put in any object - including ones that may not be appropriate to a particular use. Alas - Java is NOT a language that trusts the programmer and the compiler wails that there may be a problem (if you're a good programmer, there probably isn't a problem!).
The problem is caused by a declaration such as this:
java.util.ArrayList trowbridge =
new java.util.ArrayList();
and can be overcome by telling java what sort of objects you expect to be in the ArrayList so that it can satisfy itself by making the checks on you. Here's how you tell it:
java.util.ArrayList<Peter> trowbridge =
new java.util.ArrayList<Peter>();
(I'm my example, I have objects of class "Peter" ... Peter is actually an abstract class, and the objects are really "Rolf"s and "Steve"s.
From Java Bootcamp. See source code of this and other early examples on this course (as run this week) here
See also Java Generics