简体   繁体   English

从ArrayList返回值

[英]Returning values from an ArrayList

I had this code working for an Array...then re-read the instructions to find it specifically calls for an array LIST. 我让这段代码适用于Array ...然后重新阅读说明以找到专门用于数组LIST的指令。 I cannot seem to convert the methods beneath to be acceptable for the ArrayList...Please assist in how I need to change the verbiage...See below for a sample method: 我似乎无法将下面的方法转换为ArrayList可接受的格式...请协助我更改字词的方式...请参见以下示例方法:

public static int returnMin(ArrayList intArr) 
{  //Return the Min Value.
int minValue = intArr.get(0);
for(int i=1;i < intArr.size(); i = i+1){
    if(intArr.get(i) < minValue)
    { minValue = intArr.get(i);
    }
}   
return minValue; 
}   

try casting the objects retrieved as in 尝试投射按以下方式检索的对象

int minValue = (Integer) intArr.get(0);

and again with 并再次

if((Integer)intArr.get(i) > minValue)

In your method declaration, change: 在方法声明中,更改:
...(ArrayList intArr) { to ...(ArrayList<Integer> intArr) { . ...(ArrayList intArr) { ...(ArrayList<Integer> intArr) {
This will make the elements in intArr Integer s and not an Object s. 这将使intArr Integer的元素成为Object的元素。 To learn more about generics in java, look at The Java™ Tutorials on Generics . 要了解有关Java中泛型的更多信息,请参阅《泛型Java™教程》

As your ArrayList work only with int values, you should specify the type of your ArrayList in you method parameter: 由于ArrayList仅适用于int值,因此应在方法参数中指定ArrayList的类型:

public static int returnMin(ArrayList<Integer> intArr) { . . . }

Why to specify the type? 为什么要指定类型?

Well if you does not specify, your ArrayList will accept any value (String, Integers and any other) so when you use arrayList.get(0) you don't know what type is in that position and that is why in your example you have to cast it to Integer. 好吧,如果您未指定,则ArrayList将接受任何值(字符串,整数和任何其他值),因此当您使用arrayList.get(0)时,您不知道该位置是什么类型,这就是为什么在您的示例中必须将其转换为Integer。 Always when you are working with only one type, you should specify the type of your List to avoid this. 总是只使用一种类型时,应指定列表的类型以避免这种情况。

Generics tutorial: 泛型教程:
https://docs.oracle.com/javase/tutorial/java/generics/why.html https://docs.oracle.com/javase/tutorial/java/generics/why.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM