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.
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 Entry
s. 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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With