2017-09-09 70 views
0

我試圖找到存儲每個索引我的應用程序在多個值的簡單/快捷方式,例如:多維詞典?

1 = {54, "Some string", false, "Some other string"} 
2 = {12, "Some string", true, "Some other string"} 
3 = {18, "Some string", true, "Some other string"} 

所以,我可以將此作爲然後可以從訪問的靜態變量通過單個索引值(每個對象內唯一的變量)的各種對象實例。本質上,有點像「多維詞典」。

我已經看過二維數組,但它們似乎僅限於單一數據類型(Int,字符串等),並且還查看了哈希映射 - 這似乎也受到限制,因爲如果使用多於兩個值,將需要列表變量,它再次返回單個數據類型問題。有關這個簡單的解決方案的任何建議嗎?

+2

創建一個新班級? –

回答

2

爲這些條目定義一個類,並使用一組對象。所以,類可能是這樣的:

class Thingy { 
    private int someNumber; 
    private String someString; 
    private boolean someBool; 
    private String someOtherString; 

    public Thingy(int _someNumber, String _someString, boolean _someBool, String _someOtherString) { 
     this.someNumber = _someNumber; 
     this.someString = _someString; 
     this.someBool = _someBool; 
     this.someOtherString = _someOtherString; 
    } 

    public int getSomeNumber() { 
     return this.someNumber; 
    } 
    // ...setter if appropriate... 

    // ...add accessors for the others... 
} 

...然後你這樣做:

Thingy[] thingies = new Thingy[] { 
    new Thingy(54, "Some string", false, "Some other string"), 
    new Thingy(12, "Some string", true, "Some other string"), 
    new Thingy(18, "Some string", true, "Some other string") 
}; 
0

的Python的骨幹很大程度上依賴於字典的數據結構,很多情況下才能體現出來,分配和訪問通過使用__dict__屬性。如果你有一個模型,經常有訪問了十幾個字典左右,複製像在Python下面將減少不少不必要的Java特質的:

class ExampleObject: 
    spam = "example" 
    title = "email title" 
    content = "some content" 

obj = ExampleObject() 

print obj.spam # prints "example" 

print obj.__dict__["spam"] # also prints "example" 

只是拋出一個替代選擇那裏爲你。