, ...
SCJP . generics, . (Generics vs Arrays)
, .
, .
- " ". . , String Set
public static void main(String [] args) {
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
addString(set,"test");
for ( Object o : (Set)set ) {
System.out.println(o);
}
for ( Object o : set ) {
System.out.println(o);
}
}
public static void addString(Set set,String s) {
set.add(s);
}
:
1
2
test
1
2
ClassCastException
http://www.ideone.com/nOSQz
, ( ) , Set<Integer>, , String Integer...
( , ), , , ( ), .
- , , , , , , ...
generics , List<Dog> List<Animal> method(List<Animal>) List<Dog> param, , Cat List<Dog>, List<Animal>...
.
, , Jon Skeet sais, .
, [] [], .
, Java Cats Dog.
- .
, , , , , java...
, , , .
JVM , , .
,
Object test = new Object[2][2];
Object[] test2 = (Object [])test;
test2[0] = "blaaa";
test2[1] = "toto";
System.out.println(test2);
test (2D-) test2 (1D-), 2D-, , , 1D- A1, , 1D- A2, .
ArrayStoreException , A1 (, test2) String, , , Object, Object []
:
- 1D 2D-, 1D-, :
:
Dog[] dogs = new Dog[1];
dogs[0] = new Dog();
Animal[] animals = (Animal [])dogs;
animals[1] = new Cat();
4- .
.
Set<Dog> dogs = new HashSet<Dog>();
dogs.add( new Dog() );
Set<Animal> animals = (Set<Animal>) dogs;
animals.add( new Cat() );
- .
, , .