将通用ArrayList元素转换为基元类型(长)(Cast a generic ArrayList element into a primitive type (long))

系统教程 行业动态 更新时间:2024-06-14 16:57:39
将通用ArrayList元素转换为基元类型(长)(Cast a generic ArrayList element into a primitive type (long))

我想编写一个方法来处理一个泛型数组列表的一个元素,其中包含一个很长的数字。 我知道该数组只包含Long值,所以我不需要检查它。 这是我的方法:

searchSum(ArrayList <T> array, long n);

我需要做的对抗是:

array.get(index)==n

I 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... } } }

更多推荐

本文发布于:2023-04-13 11:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/f77d110f4b1b1e8326f1267d687109db.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   元素   类型   Cast   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!