有没有办法在java中自动为ArrayList创建对象名?

时间:2015-06-05 16:07:07

标签: java

如果是如何将字符串值作为对象名传递给ArrayList。

            int count = 0;
            String con= "contact"; 
            String generate = Integer.toString(count++);    

            String contacts = con.concat(generate);

             ArrayList<Long> // how ? // = new ArrayList<Long>();

1 个答案:

答案 0 :(得分:0)

您无法在运行时创建类似的变量,但您可以维护键/值对的映射:

Map<String, ArrayList<Long> > contactLists = new HashMap<String, ArrayList<Long> >();

// Now add each contact list to the map
int count = 0;
String generate = Integer.toString(count++);    
String key = "contact" + generate;

ArrayList<Long> currentContactList = new ArrayList<Long>();
contactLists.put(key, currentContactList);

// To get the contact list back...
ArrayList<Long> myContactList = contactLists.get("contact0");