2013-10-22 60 views
1

我有一個測試輸入文件,其中針對不同場景應創建不同數量的對象。在java中使用特定名稱創建動態對象

例如:對於一個測試輸入,它們必須是名稱爲v0,v1,v2的3個對象,而對於其他測試輸入,它們必須是名稱爲v0,v1,v2,v3,v4的5個對象。

對於5對象的靜態程序下面給出:

Vertex v0 = new Vertex("a"); 
    Vertex v1 = new Vertex("b"); 
    Vertex v2 = new Vertex("c"); 
    Vertex v3 = new Vertex("d"); 
    Vertex v4 = new Vertex("e"); 
    Vertex v5 = new Vertex("f"); 

我想讓它動態像這樣對於k = 5(無對象):

for(int i=0;i<k;i++){ 
    Vertex vi= new Vertex("str"); 
} 
+3

不,請使用數組或Map。 –

+0

Can [this](http://stackoverflow.com/questions/6729605/dynamic-variable-names-in-java)有幫助嗎? – Mateusz

+0

@Mateusz是不同的我想創建對象不可變。 – user2908533

回答

10

什麼你需要的是Map<String, Vertext>

String arr = new String[]{"a", "b", "c", "d", "e", "f"}; 
Map<String, Vertex> map = new HashMap<>(); 
for(int i = 0; i < arr.length; i++) { 
    map.put("v" + i, new Vertext(arr[i])); 
} 

然後你就可以使用它們的N檢索對象艾姆斯,例如,如果你需要v3你可以這樣寫:

Vertex v3 = map.get("v3"); // returns the object holding the String "d" 
System.out.println(v3.somevariable); 

如果somevariable持有你在構造函數傳遞字符串,然後打印語句的輸出將是

d 
+0

你能告訴我如何? – user2908533

+0

但它將如何分配值的對象。 – user2908533

+0

假設我想用'v3'像這樣: v3.somevariable – user2908533

2

你可以使用Map,其中密鑰爲String(名稱),值爲Vertex

例如爲:Map<String, Vertex>

然後,您可以這樣做:

Map<String, Vertex> testObjs = new HashMap<String, Vertex>(); 

for(int i = 0; i < k; i++) 
    testObjs.put("v" + String.valueOf(i), new Vertex(i)); 

// The names would be like v1, v2, etc. 
// Access example 
testObjs.get("v1").doVertexStuff(); 
3

這是不可能做到這一點在普通的Java。你應該能夠以某種方式使用ASM或一些字節碼操作庫來實現它,但這不值得付出努力。最好的方法是使用Map。請注意0​​是一個接口,HashMap是它的實現。

String[] names = {"v1", "v2", "v3"}; 
String[] constructorArgs = {"a", "b", "c"}; 
Map<String, Vertex> map = new HashMap<String, Vertex>(); 
for (int i = 0; i < names.length; i++) 
{ 
    map.put(names[i], new Vertex(constructorArgs[i])); 
} 

for (int i = 0; i < names.length; i++) 
{ 
    Vertex v = map.get(names[i]); 
    //do whatever you want with this vertex 
} 

您可以通過map.get(name)使用其名稱訪問變量。

有關ASM的更多信息,請參閱this answer

+0

之後,我想用'v0.adjacencies = new Edge [] {new Edge(v1,distance [0] [1])' – user2908533

+0

''你必須像'map一樣。get(「v0」)。adjacencies = ...'。在沒有操縱字節碼的情況下,真的沒有辦法實現你想要的東西。 – Mateusz