简体   繁体   中英

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

您需要将Object为int,因为- Object上没有定义-运算符,Java也不会自动取消这些。

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?

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