2016-05-29 651 views
-2

我的程序將有很多的對象,將包含字符串,布爾值和其他,我想用ID調用它們。所以我想要這樣的東西:Java - 使用名稱形式的對象字符串字符串

int ID = 1; 
void add_object() 
{ 
String IDstring = Integer.toString(ID); 
myobject IDstring = new myobject(); 
ID++; 
} 

我應該如何使這工作?或者有沒有更好的方法來做到這一點?

+1

你可以使用像'Map ' – pzaenger

+0

一致數據結構我從來沒有聽說過它,你能給我發送關於它的鏈接嗎? – Stepik

+0

我不知道你在問什麼。 –

回答

1

假設您有一個名爲Foo的類。這個類可能是你的模式,這裏存儲所有字符串,布爾等:

public class Foo { 

    private final int id; 

    public Foo(int id) { 
     this.id = id; 
    } 

    @Override 
    public String toString() { 
     return this.getClass().getSimpleName() + "[id=" + id + "]"; 
    } 
} 

此外,您有另一個類的名稱Bar,你有你的地圖:

public class Bar { 

    private final Map<Integer, Foo> map; 

    public Bar() { 
     map = new HashMap<>(); 

     map.put(0, new Foo(0)); 
     map.put(5, new Foo(5)); 
     map.put(6, new Foo(6)); 
    } 

    private void list() { 
     System.out.println(map.get(0).toString()); 
     System.out.println(map.get(5).toString()); 
     System.out.println(map.get(6).toString()); 
    } 

    public static void main(String[] args) { 
     Bar bar = new Bar(); 
     bar.list(); 
    } 
} 

我有使用一致的id將三個對象添加到地圖中。在list()內我打印這些對象。

我希望這可以幫助您開始。

看看這裏閱讀更多有關地圖:public interface Map

編輯:當然,你可以使用一個字符串來存儲ID。