开发者

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

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 开发者_JAVA技巧havent done Java for a while and i've been using VBA (where you have no datatypes), so i'm a little bit rusty.


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.


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...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜