ALL objects in Java extend Object.
Therefore it is possible to be completely non-descriptive when you create the array by declaring it an array of Objects:
Object[] arr = new Object[6];
This code creates an array of objects of length 6.
So for instance, you could create an array where entries come in pairs of two. In this case, the first object is a String and the second is an Integer.
Object[] arr = new Object[6];
arr[0] = new String("First Pair");
arr[1] = new Integer(1);
arr[2] = new String("Second Pair");
arr[3] = new Integer(2);
arr[4] = new String("Third Pair");
arr[5] = new Integer(3);
Now if you want to actually figure out what these objects are then it will require a cast:
int x = (Integer)arr[1];
Answer from M Sach on Stack OverflowALL objects in Java extend Object.
Therefore it is possible to be completely non-descriptive when you create the array by declaring it an array of Objects:
Object[] arr = new Object[6];
This code creates an array of objects of length 6.
So for instance, you could create an array where entries come in pairs of two. In this case, the first object is a String and the second is an Integer.
Object[] arr = new Object[6];
arr[0] = new String("First Pair");
arr[1] = new Integer(1);
arr[2] = new String("Second Pair");
arr[3] = new Integer(2);
arr[4] = new String("Third Pair");
arr[5] = new Integer(3);
Now if you want to actually figure out what these objects are then it will require a cast:
int x = (Integer)arr[1];
To add to the other answers, you can put whatever you want in an array of Objects. But if you wish to access any of methods or properties, not shared with Object, that a specific element has, then you have to down-cast it to the needed type as Java will recognise it as type Object - this is something you have to be careful with.
Example:
Object test[];
test = new Object[]{1, 2, "three", new Date()};
System.out.println( ( (Date)test[3] ).getMonth() );
// the above line will output '4', but there will be a compilation error
// if the cast (Date) is emitted
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<DoubleAndString> 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<DoubleAndString> - but unless that's the only natural ordering which makes sense, I'd write a Comparator<DoubleAndString>:
public class DoubleComparator implements Comparator<DoubleAndString>
{
public int compare(DoubleAndString ds1, DoubleAndString ds2)
{
return Double.compare(ds1.getDouble(), ds2.getDouble());
}
}
Then you can use Collections.sort to sort an ArrayList<DoubleAndString> or Arrays.sort to sort an array.
You can use ArrayList<Object> and you can then use anything you'd like. Encapsulate the double in a Double object and when you retrieve the object use instanceof to check if it's really a double or a String.
I must say, it's unlikely this 'design' would win you any awards. Is it possible to rethink the solution you're considering for your problem, and see if you could do with a different kind of approach?
java - Multiple type array - Stack Overflow
Java Array with multiple data types - Stack Overflow
java - How to store multiple datatypes in an array? - Stack Overflow
An array with mixed data types?
An array can only have a single type. You can create a new class like:
Class Foo{
String f1;
Integer f2;
}
Foo[] array=new Foo[10];
You might also be interested in using a map (it seems to me like you're trying to map strings to ids).
EDIT: You could also define your array of type Object but that's something i'd usually avoid.
You could create an array of type object and then when you print to the console you invoke the toString() of each element.
Object[] obj = new Object[]{"a", 1, "b", 2, "c", 3};
for (int i = 0; i < obj.length; i++)
{
System.out.print(obj[i].toString() + " ");
}
Will yield:
a 1 b 2 c 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:
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;
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.
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 arraylist
ArrayList<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.
Is it possible to create an array that can hold different types of data (strings, objects, arrays)? Should Object[ ] be used?
Thanks!
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
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.
public class Book
{
public int number;
public String title;
public String language;
public int price;
// Add constructor, get, set, as needed.
}
then declare your array as:
Book[] books = new Book[3];
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<Book> myLibrary = new ArrayList<Book>();
myLibrary.add(new Book(1, "Thinking In Java", "English", 4999));
myLibrary.add(new Book(2, "Hacking for Fun and Profit", "English", 1099);
etc.
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);
Notice the repetition of Book in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)- it screams for a class type.
class Book {
int number;
String title;
String language;
int price;
}
Now you can simply have:
Book[] books = new Books[3];
If you want arrays, you can declare it as object array an insert Integer and String into it:
Object books[3][4]
In short, you would like to call a method (like setX()) on a Way instance, or on a Pavement instance, without knowing if the object is a Way or a Pavement.
This is exactly the problem that polymorphism solves. Define an interface Locatable, and make your two classes implement this interface. Then create a List<Locatable>, and you'll be able to add Ways and Pavements inside it:
public interface Locatable {
public void setX(int x);
public void setY(int y);
public int getX();
public int getY();
}
public class Way implements Locatable {
...
}
public class Pavement implements Locatable {
...
}
List<Locatable> locatables = new ArrayList<Locatable>();
list.add(new Way());
list.add(new Pavement());
for (Locatable locatable: locatables) {
locatable.setX(22);
locatable.setY(43);
}
for (Locatable locatable: locatables) {
System.out.println("the locatable is an instance of " + locatable.getClass());
System.out.println("its location is " + locatable.getX() + ", " + locatable.getY());
}
You can use ArrayList<Object> and you check the type of the objects.
For instance:
ArrayList<Object> L = new ArrayList<Object>();
//..add objects
for (Object o : L){
if(o.getClass() == Class1.class){
Class1 obj1 = (Class1) o;
//...
}else if(o.getClass() == Class2.class){
Class2 obj2 = (Class2) o;
//...
}else{
//...
}
}
You can also use instanceof to check the type.