Multidimensional array with unknown size

最后都变了- 提交于 2019-12-23 04:33:38

问题


I need to create an array with an undefined size, which will contain user information.

For example:

user[0]["name"] = "Patrick";

However, the standard java array seems to require a known length, which I don't know.

What alternative can i use? (I'll gladly see some coding examples as well) I'm using a TCP framework (kryonet) which doesn't allow to pass objects with constructors. Therefore, as far as i can see, making a User object is not possible.


回答1:


In java we can only use integer values for cell indexes.

I guess you're looking for a list of maps:

List<Map<String, String>> persons = new ArrayList<Map<String, String>>();

// add Patrick
Map<String, String> person = new HashMap<String, String>();
person.put("name", "Patrick");
person.put("age", "23");
persons.add(person);

// add Sue
person = new HashMap<String, String>();
person.put("name", "Sue");
person.put("age", "21");
persons.add(person);

To access all names, for instance:

for (Map<String, String> person:persons) {
  System.out.println(person.get("name"));
}



回答2:


Firstly you should use Objects instead of arbitary data structures and if you don't know the size, I would use a List

List<Person> people = new ArrayList<Person>();
people.add(new Person("Patrick"));



回答3:


you cannot use associative arrays in java. In other words, you cannot use "name" as a key.

But you can create empty arrays without specifying size by doing:

String[] array = new String[]{};

However, attempting to put something into this array will give you an indexoutofbound exception




回答4:


You should consider create a class (like Person) and use only a List to manage it. The you could do something like this:

List<Peson> myLyst = new ArrayList<Person>();
Person person = new Person("Patrick");
myList.add(0, person);


来源:https://stackoverflow.com/questions/13681704/multidimensional-array-with-unknown-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!