Question

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
Was it helpful?

Solution

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));

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top