Reputation: 49
I'm having trouble trying to initiate an arraylist in which the first column I want to be a string, and the second column be a custom object.
For example column [0]
be String
, and column[1]
be an Integer
. Convention attempts of creating a multidimensional arraylist as in those used by int[][]
or String[][]
don't seem to work :( I would welcome any help. At this point I don't think it's something java allows. I can make it work for just one type of object but it's not what I want. Thanks!
Upvotes: 1
Views: 292
Reputation: 34677
Sure it does, but you weaken/eliminate type-checking:
Map myMap<String>, Integer> myData = new HashMap<String, Integer>();
Now your list of strings can be retrieved by myMap.keySet()
and values can be retrieved by myMap.values()
. Each of these return a Set, which you can easily convert to a List using the following code:
List<String> strings = new ArrayList<String>(myMap.keySet()); // get your strings
List<Integer> numbers = new ArrayList<Integer>(myMap.values(); // get your numbers
Good luck and if you should run into problems, do leave a comment.
Upvotes: 1
Reputation: 106450
Arrays are geared towards one specific type of thing - be they Object
or String
or int
. Despite the fact that you're adding multiple dimensions to them, they still only hold one type of information.
What you would rather have is a mapping between two objects. This allows you to do the following:
Here's an example. Say your custom object is a Cat
, and you want to map the name of the owner to a particular Cat
. You create a new instance of a Map.
Map<String, Cat> catOwners = new HashMap<>();
You can then put elements into it...
catOwners.put("Jamie", new Cat("Tycho"));
...and retrieve them with relative ease.
Cat currentCat = catOwners.get("Jamie"); // gets Jamie's cat
if you really want to, you can even iterate over them using the Map.Entry
object provided with all Map
s:
for(Map.Entry<String, Cat> element : catOwners.entrySet()) {
System.out.println(element.getKey()
+ " owns " + element.getValue().getName());
}
Upvotes: 1
Reputation: 27802
What you can do is use the generic Object
type, and cast accordingly.
Upvotes: 0
Reputation:
Do you need an arraylist? You could create a Map<String, Object>
or Map<String, Integer>
or whatever you need..
Upvotes: 2