Hy guys
I'm studying for
scjp. I'm doing some
test with generics in Eclipse and I've some questions
I'm learning using the scjp mcgraw hill's book .. it shows 2 examples
1st:
----
import java.util.*;
public class TestLegacy {
public static void main(
String[] args) {
List<Integer> myList = new ArrayList<Integer>();
// type safe collection
myList.add(4);
myList.add(6);
Adder adder = new Adder();
int total = adder.addAll(myList);
// pass it to an untyped argument
System.out.println(total);
}
}
import java.util.*;
class Adder {
int addAll(List list) {
// method with a non-generic List argument,
// but assumes (with no guarantee) that it will be Integers
Iterator it = list.iterator();
int total = 0;
while (it.hasNext()) {
int i = ((Integer)it.next()).intValue();
total += i;
}
return total;
}
--------
So the book says that no warnings are generated.. this because the Adder's method 'addAll' don't modify the type safe List passed in.
So I try to compile the Adder class with java1.4 and TestLegacy with java6 and no warnings comes out.. so OK!
the 2nd example:
--------
import java.util.*;
public class TestBadLegacy {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(4);
myList.add(6);
Inserter in = new Inserter();
in.insert(myList); // pass List<Integer> to legacy code
}
}
class Inserter {
// method with a non-generic List argument
void insert(List list) {
list.add(new Integer(42)); // adds to the incoming list
}
}
--------
this time I've understand that "in.insert(myList);" should give a warning!?
This because Inserter modify the list in insert() with an add..(right??).
So I compile Inserter with J1.4 and TestBadLegacy with J6 but the compiler doesn't give me a warning like 'unchecked or unsafe operations'
I need to understand exactly when are generate warnings when I use generics with old legacy code.
Thanks for your help.
