0

我有一个返回值列表的函数。我想将该列表中的值用作另一个函数中的参数。

private static List test(){
    List myList;
    mylist.add(1);
    return myList;
};

现在这是问题所在。当我说

lst = test();
myFunction(lst.get(1));

lst.get(1)是类型对象。但myFunction需要一个int。我试过把它变成很多东西。当我说(int) lst.get(1);我的编译器返回此错误时:

C:\Users\...\workspace\...\....txt
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at ///.///.Encode(///.java:73)
    at ///.///.main(///.java:25)

当我没有演员表时,我得到这个红色下划线和错误:

The method ENCODEScrambleNum(int, int, int, int, String) in the type kriptik is not applicable for the arguments (Object, Object, Object, Object, String)

方法签名:

ENCODEScrambleNum(int, int, int, int, String)

调用它:

ENCODEScrambleNum(key.get(0), key.get(1), key.get(2), key.get(3), str);

有没有办法可以事先告诉计算机列表类型将是 int?

谢谢。

4

3 回答 3

2

哦,是的,你可以这样做。只需像这样声明列表的类型

private static List<Integer> test(){
    //List<Integer> myList; // list is not initialized yet(NPE is waiting for you)
    List<Integer> myList = new ArrayList<Integer>(); // List initialized
    mylist.add(1);
    return myList;
} // Why was a semi-colon here?

当您尝试list.get(1)作为int参数发送时,它将被自动装箱。所以你不必担心。

于 2013-10-11T04:07:19.680 回答
2
private static List test(){
    List myList;
    mylist.add(1);    //Here the value 1 is added at zeroth index.
    return myList;
}

将您的代码替换为

lst = test();
myFunction(lst.get(0));  //Retrieves the value at zeroth index.

代替,

lst = test();
myFunction(lst.get(1)); //Retrieves the value at first index

因为List索引0从而不是从开始1

于 2013-10-11T04:16:44.760 回答
0

我同意 RJ,如果您将列表类型指定为整数并使用 get() 函数,它将始终返回一个整数。我尝试了以下代码,希望对您有所帮助:

private static List<Integer> test(){

List<Integer> myList = new ArrayList<Integer>(); 
for(int i=0; i<4; i++){ myList.add(i+10);} //included a for loop just to put something in the list
return myList;
}

private static String ENCODEScrambleNum(Integer get, Integer get0, Integer get1, Integer get2, String in_here) {
     return "I am " + in_here + " with list items-" + get + get0 + get1 + get2; //Dummy logic
}
于 2013-10-11T06:17:44.667 回答