简体   繁体   中英

How can we add two objects from a ArrayList <Object>?

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?

  1. Object as type parameter can allow the collection to hold any type of java object
  2. Though this simplifies the writers, it places a huge burden on the readers to validate the types to avoid run time ClassCastException s. It behaves like pre-generic world

Regarding why list.get() is allowed in c and d :

  1. 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 )
  2. same applies for list.get(2)
  3. if you meant about casting the reference before making a method call, then it will look like ((int)list).get(0)) . Unfortunately this is invalid due to the types used.

More

  1. Actually it will be interesting to add a long to the list list.add(1L)
List<Object> list = new ArrayList<>();
list.add(1L);
(int) list.get(0) + (int) list.get(0);
  1. Casting this to int will result in run time ClassCastException (something like Long cannot be cast to Integer )
  2. This is because, even though, we apply the cast as primitive 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM