【问题标题】:Assume list type is int java假设列表类型是 int java
【发布时间】:2013-10-19 01:23:15
【问题描述】:

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

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?

谢谢。

【问题讨论】:

    标签: java arrays list types casting


    【解决方案1】:

    我同意 R.J,如果您将列表类型指定为整数并使用 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
    }
    

    【讨论】:

    • 它仍然表现得像key.get(1); 是一个对象。它不会将其识别为整数。
    【解决方案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

    【讨论】:

    • 试过了,没用。不过,谢谢。
    【解决方案3】:

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

    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 参数发送时,它将被自动装箱。所以你不必担心。

    【讨论】:

    • 嗯...仍然得到相同的编译错误。仍然表现得像物体一样。
    • 您能否发布您的myFunction() 方法的签名,以及您究竟是如何使用list 条目作为参数来调用它的?
    • String numText = ENCODEScrambleNum(key.get(1), key.get(2), key.get(3), key.get(4));
    • 假设key = test()
    • 请编辑您的问题并发布方法签名以及那里的调用。在这里发布代码会使 cmets 相当笨拙。
    猜你喜欢
    • 2022-12-05
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2012-03-15
    • 2013-10-26
    • 2015-05-02
    • 2013-04-29
    相关资源
    最近更新 更多