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?
5 Answers 5
I am not sure I am following, but you might be looking for a Map . or Map> . [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> if you want to attach more then one String per Integer , or alternatively you can use apache commons MultiMap
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.
I am sorry but I am not sure what do you mean by: «each element of the array is a reference to the entire DB row». The entire DB row is made up of two columns of different types, string and int. How can I store it in one array?
What are you using to access the database? There must be an object that represents a row in a table. Then that row must have methods you can call to access the column data in that row. Whatever object wraps the database row is what you need to store in your array. I mean, that’s essentially what a database table is — an array of rows.
How to declare an array of different data types [closed]
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
I am working with arrays in Java and I have got a question. I know that an array in Java is a collection of similar data types, as shown below:
The above declaration can be read as an Integer array which is a collection of integer types. Consider this:
Here, can I say that the above is an array which is a collection of dis-similar data types, or is it an Object array of similar data types, i.e. objects? I am muddled and skeptical about this. In Java, is it possible to create an array or any sort of collection which can hold different data types?
@duffymo, Treating the JDK as an expert only works for things on which most JDK implementations are likely to agree and won’t reliably suss out strange cases like array variance in Java.
For something like this, which has been possible since JDK 1.0, I’d disagree. And all the more reason to suss out strange cases for your JDK. Are you suggesting that «expert» advice here will suss them out more efficiently?
@duffymo, I assert that questions of the form «is this idiomatic in language X», «does this have pitfalls», and «is this speced or peculiar to my test environment» should be tested and put to experts. I assert that heterogeneous arrays touch on all three of those forms, since different languages have different alternative approaches (Haskell) or idiomatic preference (Ruby vs C void*) so it is reasonable to wonder what is idiomatic in Java; pitfalls are precisely what you are unlikely to find until you trip over them (etymology of «pitfall»); many languages have undefined behavior.
Arrays of different types
Is it possible to have an array that contains two different types of data? I want to have an array that contains a double and also a string. I attempted:
But that didn’t work. Sorry for the silly question, but it has been a while since I have used something like this.. Can you refresh my memory on how would I declare and populate such an array? And then to take it a step further, I would like to sort the array by the double if possible? Thanks!
No, this is not possible. What exactly are you trying to do? Maybe we can help you come up with a workaround.
10 Answers 10
Firstly, it’s worth being clear about the difference between an array and an ArrayList — they’re not the same thing at all.
However, in either case you can’t do what you want. The closest you can probably come is declaring your own type. (EDIT: My original code had a double or a string. I’ve now changed it to be a double and a string. Let me know if this change isn’t what you had in mind.)
public final class DoubleAndString < private final String stringValue; private final double doubleValue; public DoubleAndString(String stringValue, double doubleValue) < this.stringValue = stringValue; this.doubleValue = doubleValue; >public String getString() < return stringValue; >public String getDouble() < return doubleValue; >>
Then create an ArrayList or a DoubleAndString[] .
Now, this feels somewhat vanilla at the moment — presumably the double and string values actually have a greater meaning — a name and a score, for example. If so, encapsulate that in a type which describes the pairing more appropriately.
As for ordering — you could make DoubleAndString implement Comparable — but unless that’s the only natural ordering which makes sense, I’d write a Comparator :
public class DoubleComparator implements Comparator < public int compare(DoubleAndString ds1, DoubleAndString ds2) < return Double.compare(ds1.getDouble(), ds2.getDouble()); >>
Then you can use Collections.sort to sort an ArrayList or Arrays.sort to sort an array.
Java Array with multiple data types
What can I use to store multiple different types of data, Int/String/etc.? I come from a PHP background where I can store different types of data into an array, but I don’t know how to do that in Java. Take this example:
$array = array( "val1" => 1, "val2" => "cat", "val3" => true );
How is this a duplicate? I disagree. This is a different question from the one it’s marked a duplicate of.
Closed so I cant answer but I’d use a typesafe heterogenous container as described in Effective Java (and linked to earlier in this sentence). The typesafe heterogenous container solves the problem of retrieving objects later by allowing you to find out the class of what is stored at each location in the map.
3 Answers 3
Java is a strongly typed language. In PHP or Javascript, variables don’t have a strict type. However, in Java, every object and primative has a strict type. You can store mutliple types of data in an Array, but you can only get it back as an Object.
You can have an array of Objects:
Object[] objects = new Object[3]; objects[0] = "foo"; objects[1] = 5;
Note that 5 is autoboxed into new Integer(5) which is an object wrapper around the integer 5.
However, if you want to get data out of the array, you can only get it as an Object. The following won’t work:
int i1 = objects[1]; // Won't work. Integer i2 = objects[2]; // Also won't work.
You have to get it back as an Object:
Object o = objects[0]; // Will work.
However, now you can’t get back the original form. You could try a dangerous cast:
However you don’t know that o is a String.
You can check with instanceof :
String s = null; if (o instanceof String) s = (String) o;
This will certainly work but you’re going to have to instanceof every item you get from the array, requiring a conditional as long as the number of object types stored in the array.
You could use an object array but that creates problems when the time comes to retrieve the objects you have stored. Instead I would use a typesafe heterogenous container as described in Effective Java (and linked to earlier in this sentence).
public class DateStuff< private Map, Object> dateMap = new HashMap, Object>(); public void putDate(Class type, T instance) < if(type == null) throw new NullPointerException("Type null"); dateMap.put(type, instance); >public getDate(Class type) < return type.cast(dateMap.get(type)); >>
The typesafe heterogenous container solves the problem of retrieving objects later by mapping objects by their class. In your case I would combine this with other data structures — for example List , List , or List , as the base classes to provide a way to store multiple different kinds of objects in one collection. Then to retrieve values you would simply get the sub collection, e.g. a List , knowing that all items contained therein were of the same class.
Arrays with different datatypes i.e. strings and integers. (Objectorientend)
For example I have 3 books: Booknumber (int) , Booktitle (string) , Booklanguage (string) , Bookprice (int) . Now, I want to have an array called books[3][4] . I’m getting the data I set via setBooknumber like this:
Book1.getBooknumber(), Book1.getBooktitle(). Book3.getBookprice(). How do I realize this: books[3][4] array . I can’t call it String books[][] = new String [3][4] . Because I can’t get Booknumber (int) into it. I don’t want Booknumber to be String neither Bookprice. How do I realize it, please? To further elaborate it. I have 2 classes: book and bookUI. book
Because it’s what I’m trying to get working. Doesn’t matter how ugly it is or how stupid. It’s my own goal and I want to do it so I can understand why it didn’t work, how it works, and LATER ON how to do it different.
OK then the simple solution is: There is no way to access class properties in this array[0] style. (correct me if I’m wrong). Arrays are also typed so the only solution is to create an array of arrays of Objects which is bad as you have to know what object type you are actually dealing with (String or Integer). OOP is there to make life easier for you just accept it.
-1: If you are not willing to accept that some things are not possible than nobody can help you. It is like you gave us water and asked us to cook pasta without pasta and a pot (and in time for dinner).
Felix is correct. Arbitrary objects are not arrays and you can’t use array syntax on them. That just isn’t Java.
5 Answers 5
then declare your array as:
EDIT: In response to O.P.’s confusion, Book should be an object, not an array. Each book should be created on it’s own (via a properly designed constructor) and then added to the array. In fact, I wouldn’t use an array, but an ArrayList. In other words, you are trying to force data into containers that aren’t suitable for the task at hand.
I would venture that 50% of programming is choosing the right data structure for your data. Algorithms naturally follow if there is a good choice of structure.
When properly done, you get your UI class to look like: Edit: Generics added to the following code snippet.
. ArrayList myLibrary = new ArrayList(); myLibrary.add(new Book(1, "Thinking In Java", "English", 4999)); myLibrary.add(new Book(2, "Hacking for Fun and Profit", "English", 1099);
now you can use the Collections interface and do something like:
int total = 0; for (Book b : myLibrary) < total += b.price; System.out.println(b); // Assuming a valid toString in the Book class >System.out.println("The total value of your library is " + total);