2012-05-01 25 views
12

我需要的東西就像一個3維(如列表或地圖),我充滿了2串一個循環內的整數。但是,不幸的是,我不知道要使用哪種數據結構以及如何使用。3維度列表或地圖

// something like a 3-dimensional myData 
for (int i = 0; i < 10; i++) { 
    myData.add("abc", "def", 123); 
} 
+0

什麼是三個數值之間的關係? – Attila

+0

它們來自JTextFields和JButtons。 – user1170330

+0

好的,但是你想和他們一起做嗎? – Attila

回答

18

創建封裝三者共同的目標,並把它們添加到一個數組或列表:如果要插入到數據庫

public class Foo { 
    private String s1; 
    private String s2; 
    private int v3; 
    // ctors, getters, etc. 
} 

List<Foo> foos = new ArrayList<Foo>(); 
for (int i = 0; i < 10; ++i) { 
    foos.add(new Foo("abc", "def", 123); 
} 

,寫一個DAO類:

public interface FooDao { 
    void save(Foo foo);  
} 

根據需要使用JDBC實現。

+0

我需要一個類似的「容器」類才能存儲三個屬性。我通過構造函數初始化這些屬性,並且我需要分別訪問每個屬性。該類沒有任何邏輯,只有這三個屬性和一個構造函數。訪問這些屬性的最佳方式是什麼?在這種情況下,將屬性設置爲public okay,或者我應該寫getters?這些屬性是最終的。 – kazy

+1

好嗎?誰會阻止你?讓他們公開最後;他們是不可改變的。 OO警察會來敲門。 – duffymo

+0

我在問是否可以,因爲我不想編寫違反面向對象概念的東西。從你的回答中,我假定最終的屬性不需要獲取者,因爲它們無法改變?或者只是在這種小案件的情況下才是「最終公開」? – kazy

2

只需創建一個類

class Data{ 
    String first; 
    String second; 
    int number; 
} 
1

答案取決於什麼值之間的關係是。

1)您只需要按照它們的順序存儲所有三個元素:創建一個包含所有三個元素的自定義類,並將此類的實例添加到List<MyData>

2)您想將第一個字符串與第二個和第三個數據相關聯(並將第二個數據與int相關聯):創建一個Map>並添加元素(您將必須創建內部地圖爲每個新的第一個字符串)

3)你不想保留重複,但你不想要/需要一張地圖:創建一個自定義類型(a'la 1)),並把它們放在一個Set<MyData>

3)混合和匹配

9

一個谷歌的Guava代碼應該是這樣的:

上述
import com.google.common.collect.Table; 
import com.google.common.collect.HashBasedTable; 

Table<String, String, Integer> table = HashBasedTable.create(); 

for (int i = 0; i < 10; i++) { 
    table.put("abc", "def", i); 
} 

代碼將構造一個HashMap的內部是一個HashMap與構造,看起來像這樣:

Table<String, String, Integer> table = Tables.newCustomTable(
     Maps.<String, Map<String, Integer>>newHashMap(), 
     new Supplier<Map<String, Integer>>() { 
    @Override 
    public Map<String, Integer> get() { 
     return Maps.newHashMap(); 
    } 
}); 

如果你想覆蓋的基本結構,你可以很容易地改變它。

-1

你可以用這個代碼去!

public class List3D { 

    public static class MyList { 
     String a = null; 
     String b = null; 
     String c = null; 

     MyList(String a, String b, String c) { 
      this.a = a; 
      this.b = b; 
      this.c = c; 
     } 
    } 

    public static void main(String[] args) { 

     List<MyList> myLists = new ArrayList<>(); 
     myLists.add(new MyList("anshul0", "is", "good")); 
     myLists.add(new MyList("anshul1", "is", "good")); 
     myLists.add(new MyList("anshul2", "is", "good")); 
     myLists.add(new MyList("anshul3", "is", "good")); 
     myLists.add(new MyList("anshul4", "is", "good")); 
     myLists.add(new MyList("anshul5", "is", "good")); 

     for (MyList myLista : myLists) 
      System.out.println(myLista.a + myLista.b + myLista.c); 
    } 
}