2017-05-05 54 views
1

我對Java很新,我有一個小問題。我有一個函數返回String和一個返回int的函數,我必須把它們放到一個看起來像這樣的列表({String, int},{String, int})。我最好怎麼做?java問題建立一個specefic結構列表

+0

你應該bean類的這個或使用收集API。使用HashMap中] –

+2

無論是'地圖<字符串,整數>'或'名單'。 –

+0

我不知道我是否理解這個問題,但是Java中沒有像在Python中那樣的元組。將這兩個值封裝在某種對象中,並將它們添加到列表中。 – duffymo

回答

0

如果你的問題是@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); 
    } 
}