[英]Cast a generic ArrayList element into a primitive type (long)
I would like to write a method which confronts an element of a generic ArrayList with a long number. 我想写一个面对带有长数字的通用ArrayList元素的方法。 I know that the array contains only Long values, so I don't need to check this.
我知道该数组仅包含Long值,因此不需要检查此值。 This is my method:
这是我的方法:
searchSum(ArrayList <T> array, long n);
The confrontation I need to do is: 我需要做的对抗是:
array.get(index)==n
You cannot cast list to primitives. 您不能将列表强制转换为基元。 Java list contains Objects and the primitives are not objects.
Java列表包含对象,而基元不是对象。 But depending on what you want to do I am pretty sure there is an easy way to achieve it.
但是,根据您要执行的操作,我很确定有一种简单的方法可以实现它。 Unfortunately from your question I can hardly understand what is the goal.
不幸的是,从您的问题中我很难理解目标是什么。
If you want to find if the list contains an element you can use: 如果要查找列表中是否包含元素,可以使用:
array.indexOf(new Long(n));
and it will tell you the index of the first ocurance of the element. 它将告诉您该元素的第一个出现次数的索引。
If you just want to see if it is there you can use array.contains(new Long(n));
如果只想看看它是否在那里,可以使用
array.contains(new Long(n));
If you want to sum all elements (since your method is called searchSum) you can do: 如果要对所有元素求和(因为您的方法称为searchSum),则可以执行以下操作:
searchSum(ArrayList <T> array, long n){
for (Long element: array){
if(Long.valueOf(n).equals(element)){
.... do something here...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.