Reputation: 3
Is it possible to store multiple objects in a single array element and if so, what would be the best method to go about doing that?
Upvotes: 0
Views: 1714
Reputation: 18968
You can store anything in an Object[]
object array.
Something like this:
Object[] objArr = new Object[10];
objArr[0] = "String";
objArr[1] = Arrays.asList(1, 2, 4);
objArr[2] = new ArrayList<>();
objArr[3] = 1;
Upvotes: 0
Reputation: 24711
No. Any given element of an array is just that, one element. The type of element does matter, though.
Consider an array of integers:
int[] x = {1, 4, 7, 10};
One element cannot 'hold' multiple elements.
But now consider an array of arrays of integers:
int[][] x = {
{1},
{2, 3},
{4, 5, 6},
{7, 8, 9, 10}
};
Each element is still just a single element. There are four elements each of type int[]
. Then, each of those has one element per element. You can theoretically have as many layers of this as you want. It can get confusing very quickly.
Another way to fit 'multiple elements into one element' would be to write your own class that holds multiple elements in whatever way is most useful to you, and make an array of those.
Note: above, I've used primitive arrays to demonstrate. However, this also works with Java List
objects:
ArrayList<Integer> x; // list of integers
ArrayList<ArrayList<Integer>> x; // list of ArrayList<Integer> objects, each of which is itself a list of integers
ArrayList<Integer>[] x; // primitive array of ArrayList<Integer> objects
// (I recommend not doing this, it can get confusing)
If your question is about putting multiple types of objects in a single element, then you have to figure out what superclass encompasses both types (usually Object
, if the types are remotely different), and make your list that type:
Object[] x = {Integer.valueOf(5), Double.valueOf(3.14), "some_string"};
Getting those objects back out again and putting them into their correct type, is difficult, so I don't recommend this.
You can also try building your own Union
type, and making the list be that type.
Upvotes: 1