List of objects. Operations with Integer entries
-
17-04-2021 - |
質問
The List might contain both Integers and String values. In this case, should I create the List of Objects, right?
List<Object> list = new ArrayList<Object>();
How to perform simple arithmetic operations with the Integer entries of the List?
list.add(1);
list.add("ok");
list.add(2);
Integer a = list.get(0) - list.get(2); // does not work
解決
You need to cast the Object
s to int, because the -
Operator isn't defined on Object
s and Java does not unbox these automatically.
Integer a = ((Integer)list.get(0)) - ((Integer)list.get(2));
他のヒント
That's because ultimately, list.get(0);
is an Object
. You have to cast it if you want to do arithmetic operations on it:
Integer a = (Integer) list.get(0) - (Integer) list.get(2);
This is a really bad design to be honest. What if you want to iterate over that list? You will have to manually check if the element is a string or an integer. Generics where introduced to Java for a reason.
Can't you make 2 lists: one for strings and one for integers. Or at least use one list but instead of using strings use a (normally unused) integer value?