我想编写一个方法来处理一个泛型数组列表的一个元素,其中包含一个很长的数字。 我知道该数组只包含Long值,所以我不需要检查它。 这是我的方法:
searchSum(ArrayList <T> array, long n);我需要做的对抗是:
array.get(index)==nI would like to write a method which confronts an element of a generic ArrayList with a long number. I know that the array contains only Long values, so I don’t need to check this. This is my method:
searchSum(ArrayList <T> array, long n);The confrontation I need to do is:
array.get(index)==n最满意答案
您无法将列表转换为基元。 Java列表包含对象,并且基元不是对象。 但取决于你想做什么,我很确定有一个简单的方法来实现它。 不幸的是,从你的问题,我很难理解目标是什么。
如果您想查找列表是否包含您可以使用的元素:
array.indexOf(new Long(n)); 它会告诉你元素的第一次提示的索引。
如果你只是想看看它是否存在,你可以使用array.contains(new Long(n));
如果你想总结所有元素(因为你的方法被称为searchSum),你可以这样做:
searchSum(ArrayList <T> array, long n){ for (Long element: array){ if(Long.valueOf(n).equals(element)){ .... do something here... } } }You cannot cast list to primitives. Java list contains Objects and the primitives are not objects. 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));
If you want to sum all elements (since your method is called searchSum) you can do:
searchSum(ArrayList <T> array, long n){ for (Long element: array){ if(Long.valueOf(n).equals(element)){ .... do something here... } } }更多推荐
发布评论