问题
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