Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of objects. Operations with Integer entries

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
like image 639
Klausos Klausos Avatar asked Mar 04 '26 13:03

Klausos Klausos


2 Answers

You need to cast the Objects to int, because the - Operator isn't defined on Objects and Java does not unbox these automatically.

Integer a = ((Integer)list.get(0)) - ((Integer)list.get(2));
like image 191
Matten Avatar answered Mar 06 '26 02:03

Matten


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);
like image 22
Milad Naseri Avatar answered Mar 06 '26 03:03

Milad Naseri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!