Search code examples
javaarrayskryonet

Multidimensional array with unknown size


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 () which doesn't allow to pass objects with constructors. Therefore, as far as i can see, making a User object is not possible.


Solution

  • 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"));
    }