How to store multiple datatypes in an array? How to store multiple datatypes in an array? arrays arrays

How to store multiple datatypes in an array?


You can use an ArrayList.

ArrayList<Object> listOfObjects = new ArrayList<Object>();

And then add items to it.

listOfObjects.add("1");listOfObjects.add(someObject);

Or create your own object that encapsulates all the field that you require like

public class LocationData {   private double lat;   private double longitude;   public LocationData(double lat, double longitude) {       this.lat = lat;       this.longitude = longitude;   }   //getters   //setters}

and then add your lat/long pairs to an ArrayList of type LocationData

ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();listOfObjects.add(new LocationData(lat, longitude));


You can create an array of your Custom-Class.

public class YourCustomClass {     String id;     String name;     double longitude;     // and many more fields ...    public YourCustomClass() {  // constructor     }    public void setID(String id) {        this.id = id;    }    public String getID() {        return id;    }    // and many more getter and setter methods ...}

Inside your custom-class you can have as many fields as you want where you can store your data, and then use it like that:

// with array YourCustomClass [] array = new YourCustomClass[10];array[0] = new YourCustomClass();array[0].setID("yourid");String id = array[0].getID();// with arraylistArrayList<YourCustomClass> arraylist = new ArrayList<YourCustomClass>();arraylist.add(new YourCustomObject());arraylist.get(0).setID("yourid");String id = arraylist.get(0).getID();

You can also let the AsyncTasks doInBackground(...) method return your Custom-class:

protected void onPostExecute(YourCustomClass result) { // do stuff...}

Or an array:

protected void onPostExecute(YourCustomClass [] result) { // do stuff...}

Or a ArrayList:

protected void onPostExecute(ArrayList<YourCustomClass> result) { // do stuff...}

Edit: Of course, you can also make a ArrayList of your custom object.


You should consider the use of the typesafe heterogeneous container pattern.

There the data is stored in a Map<Key<?>, Object> and access to the map is hidden behind generic methods, that automatically cast the return value.

public <T> T getObjectByKey(Key<T> key)  return (T) map.get(key);

The same for put.