[英]List of objects. Operations with Integer entries
The List might contain both Integers and String values. List可能包含Integers和String值。 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的Integer条目执行简单的算术运算?
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);
那是因为最终,
list.get(0);
is an Object
. 是一个
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.
出于某种原因引入Java的泛型。
Can't you make 2 lists: one for strings and one for integers. 你不能制作2个列表:一个用于字符串,一个用于整数。 Or at least use one list but instead of using strings use a (normally unused) integer value?
或者至少使用一个列表但不使用字符串使用(通常未使用的)整数值?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.