13

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 can I make something similar in Java?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • 1
    Take a look at [HashMaps](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html). – PakkuDon May 30 '14 at 14:59
  • Don't you have to define your values using a HashMap? – Get Off My Lawn May 30 '14 at 14:59
  • 2
    `Object[]` is your friend and enemy – Dmitry Zaytsev May 30 '14 at 15:00
  • @Ryan Naddy yes you do. You could simply use and Object[] then use Integer and Boolean instead of the native int and boolean type. – Jean-François Savard May 30 '14 at 15:01
  • 1
    How is this a duplicate? I disagree. This is a different question from the one it's marked a duplicate of. – Anubian Noob May 30 '14 at 15:03
  • 1
    Closed so I cant answer but I'd use a [typesafe heterogenous container](http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA142&lpg=PA142&dq=effective+java+heterogeneous+container&source=bl&ots=yZCgMkp_T3&sig=md9i2cEOP5e7M8u5cenpBw5titw&hl=en&sa=X&ei=op2IU5r3JZbJsQS-w4GwBA&ved=0CDIQ6AEwAQ#v=onepage&q=effective%20java%20heterogeneous%20container&f=false) 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. – Rarw May 30 '14 at 15:13
  • @Rarw That's probably a better answer. Pushing for a reopen... – Anubian Noob May 30 '14 at 15:19

3 Answers3

26

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:

String s = (String) o;

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;
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • 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. – Rarw May 30 '14 at 16:17
4

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<Class<?>, Object> dateMap =
        new HashMap<Class<?>, Object>();

    public <T> void putDate(Class<T> type, T instance){
          if(type == null)
              throw new NullPointerException("Type null");
          dateMap.put(type, instance);
    } 

    public<T> getDate(Class<T> 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<Date>, List<String>, or List<Integer>, 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<Date>, knowing that all items contained therein were of the same class.

Rarw
  • 7,645
  • 3
  • 28
  • 46
0

This post is meant to be a simpler one

You can use the built-in Object class to create an array that supports Strings, Integers, etc.

Example:

Object[] x = {"Item 1", 2, null, true};
Macintosh Fan
  • 355
  • 1
  • 4
  • 18