Featured post
Java generics - ArrayList initialization -
it known arraylist init. should this
arraylist<a> = new arraylist<a>(); arraylist<integer> = new arraylist<number>(); // compile-time error
so, why java allow these ?
1. arraylist<? extends object> a1 = new arraylist<object>(); 2. arraylist<?> a2 = new arraylist<integer>();
then, if correct why doesn't allow these ?
1. a1.add(3); 2. a2.add(3);
the compiler message : method add(int, capture#1-of ? extends object) in type arraylist not applicable arguments (int)
more general
1. a1.add(null e); 2. a2.add(? e);
i read hear you. thanks
the other amusing point :
arraylist<arraylist<?>> = new arraylist<arraylist<?>>(); // correct arraylist<?> = new arraylist<?>(); // wrong. know it's reason have question in mind mentioned above
you can't assign list<number>
reference of type list<integer>
because list<number>
allows types of numbers other integer
. if allowed that, following allowed:
list<number> numbers = new arraylist<number>(); numbers.add(1.1); // add double list<integer> ints = numbers; integer fail = ints.get(0); // classcastexception!
the type list<integer>
making guarantee contains integer
. that's why you're allowed integer
out of without casting. can see, if compiler allowed list
of type such number
assigned list<integer>
guarantee broken.
assigning list<integer>
reference of type such list<?>
or list<? extends number>
legal because ?
means "some unknown subtype of given type" (where type object
in case of ?
, number
in case of ? extends number
).
since ?
indicates do not know specific type of object list
accept, isn't legal add null
it. are, however, allowed retrieve object it, purpose of using ? extends x
bounded wildcard type. note opposite true ? super x
bounded wildcard type... list<? super integer>
"a list of unknown type @ least supertype of integer
". while don't know type of list
(could list<integer>
, list<number>
, list<object>
) know sure whatever is, integer
can added it.
finally, new arraylist<?>()
isn't legal because when you're creating instance of paramterized class arraylist
, have give specific type parameter. use whatever in example (object
, foo
, doesn't matter) since you'll never able add null
since you're assigning directly arraylist<?>
reference.
- Get link
- X
- Other Apps
Comments
Post a Comment