lunar
lunar

Reputation: 1232

Two-dimensional array of different types

I want to create a two-dimensional array in which I want to store records from the database. So lets say that the first is of type int and the second of type String (here I am describing just one record so basically types of db columns). How can I do it? Is an array the right data structure for that?

Upvotes: 19

Views: 89662

Answers (5)

user3182445
user3182445

Reputation: 363

If you simply want to have one column of String data and another column of int data, this is what you can consider doing:

Declare a 2 dimensional String array

String[][] words = new String[][];

Your first column can contain all the String data. The second column can have the numeric data but in the form of a String. You may want to use the Integer.toString() and Integer.parseInt() methods to do this

words[index][index] = Integer.toString(Integer.parseInt(args));

I'm not sure what exactly you hope to achieve but you may consider modifying this snippet to suit your needs

Upvotes: 2

amit
amit

Reputation: 178421

I am not sure I am following, but you might be looking for a Map<Integer,String>. or Map<Integer,List<String>>. [have a look on List, and HashMap]

Map allows association of the key [Integer] to the value [String or List].

Map also allows fast lookup of key, and its attached value.

(*) You should use Map<Integer,List<String>> if you want to attach more then one String per Integer, or alternatively you can use apache commons MultiMap

Upvotes: 15

Yogesh Prajapati
Yogesh Prajapati

Reputation: 4870

You can do the same thing with the help of this

Object[][] o = new Object[10][10];

o[0][0] = 1;
o[0][1] ="hello";

System.out.println(o[0][0]);
System.out.println(o[0][1]);

Upvotes: 5

Lior Barnea
Lior Barnea

Reputation: 236

You can use

HashMap<Integer, ArrayList<String>>

Upvotes: 3

jefflunt
jefflunt

Reputation: 33954

Arrays can only contain one type. If that type happens to be Object then it can store Object and any of its sub-types, but that doesn't really sound like what you're trying to accomplish here.

It sounds like what you're describing is a 2D array to store database information, with each element in the array being a column in one of the rows. This isn't an array of records, it's an array of column data.

Instead, just store a one-dimensional array of records, where each element of the array is a reference to the entire DB row.

Upvotes: 9

Related Questions