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 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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With