I recently started studying Java's ArrayList
class, and learned about how we can use an ArrayList <Object>
to hold elements of different class types. This question, however, confused me.
My general thinking pattern in answering this question was that we can first eliminate answers A and B, because the compiler would complain about using the +
operator on two Objects that have not been cast. When I looked at answers C and D, however, it seemed to me that both of them would work correctly, because they both cast the values returns from list.get()
to a type where the operator +
is defined. This led me to choose answer E, as I believed both C and D could work in this piece of code.
As you can see, however, E was the wrong answer. To compound my confusion, I tested this piece of code on repl.it, where it was confirmed that answer choices A and B result in compilation errors while answer choices C and D both store the correct value of 9
into i
. So now, I'm really confused. Is there some rule with Object
s that I am glossing over here? Can someone point me in the right direction?
Object
as type parameter can allow the collection to hold any type of java object ClassCastException
s. It behaves like pre-generic worldRegarding why list.get()
is allowed in c
and d
:
list.get(0)
will be first invoked and the result is casted to int
. (since the type of values stored at 0
is Integer
, it is perfectly valid to cast as int
- actually cast to Integer
and then unbox to int
) list.get(2)
((int)list).get(0))
. Unfortunately this is invalid due to the types used.list.add(1L)
List<Object> list = new ArrayList<>();
list.add(1L);
(int) list.get(0) + (int) list.get(0);
int
will result in run time ClassCastException
(something like Long cannot be cast to Integer
)int
, it actually does an evaluation of object hierarchy based on the reference(object type) and finds that Integer
and Long
are siblings and does not have a direct hierarchy and hence throw an ClassCastException
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.