Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, easiest way to store mixed-data types in a multidimensional array?

Tags:

java

Ive got a file with some String and ints I wish to store in a 2D 'array'. What is the best way of doing this? I havent done Java for a while and i've been using VBA (where you have no datatypes), so i'm a little bit rusty.

like image 524
James Avatar asked Dec 17 '22 14:12

James


2 Answers

Make it a two dimensional array of Objects, if you must.

A better solution is to find a common interface, and make it a two dimensional array of that interface.

The best solution is to do something like

public class Entry {

  private String name;

  private int value;

  public Entry(String name, int value) {
    this.name = name;
    this.value = value;
  }

  public String getName() {
    return this.name;
  }

  public int getValue() {
    return this.value;
  }

}

And make it a single dimensional array of Entrys. Note that if you really wanted to "go for the gold" rename the above Entry class to a class name that actually makes sense.

like image 184
Edwin Buck Avatar answered May 06 '23 05:05

Edwin Buck


If the strings and the integers are in any relation, maybe a map might help you. Example, if you have strings, that map to integers (int and Integer can be easily converted. Read up on autoboxing):

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Teststring", 5);

This would be for a lookup list, where order is not important. If you need ordering, use for example a TreeMap.

Also you should check out Apache Commons IO, which is a free library that can be a huge help in handling files. (Like almost everything in Apache Commons. These libraries have saved my sanity/job/life more than once...)

like image 36
nfechner Avatar answered May 06 '23 03:05

nfechner