我是Java的新手,我有一个小问题。我有一个返回String的函数和一个返回int的函数,我必须将它们放入类似此({String, int},{String, int})的列表中。我最好怎么做?

最佳答案

如果您的问题是@duffymo在其评论中描述的内容,那么我认为Java不会这样做。但是,您可以通过创建具有两个字段的类来全面解决问题。

private String methodForString() {
    String result = new String();
    // ... your code which manipulates result
    return result;
}

private int methodForInt() {
    int result = 0;
    // ... your code which manipulates result
    return result;
}

class MyClass {
    String returnString;
    int returnInt;

    public String getReturnString() {
        return returnString;
    }

    public void setReturnString(String returnString) {
        this.returnString = returnString;
    }

    public int getReturnInt() {
        return returnInt;
    }

    public void setReturnInt(int returnInt) {
        this.returnInt = returnInt;
    }
}

private void initializingMethod() {
    List<MyClass> list = new ArrayList<>();
    int numberItems = 100;// this represents the number of items you want to
                            // put in your list
    for (int i = 0; i < numberItems; i++) {
        MyClass myClass = new MyClass();
        myClass.setReturnInt(methodForInt());
        myClass.setReturnString(methodForString());
        list.add(myClass);
    }
}

10-07 22:53