Reputation: 21
Is it possible in java to store multiple objects in one array index. For example object1 and object2 which are string variables can be referenced by array[1].
String[] text = new String []
text[1]="rabbit"
text[1]="horse"
So now if I outputted text[1] it would output both strings "rabbit" and "horse".
And is it possible for one object to be reference several array indexs. For example say that object1 = array[1] and array[2].
I'm more interest in the first example. And if they are possible can you please give me an example of this in action.
Upvotes: 0
Views: 71
Reputation: 16384
So now if I outputted text[1] it would output both strings "rabbit" and "horse".
No this won't work because String
is an Object
and since java object references can hold only one reference to an object at a time, it won't be possible.
So either your text[1]
will reference a String
with characters rabbit or horse
You have to review your application/method design and you can use some other API Classes which can help achieve your need such as ArrayList
List<List<String>> myList = new ArrayList<ArrayList<String>>();
myList.add(new ArrayList<String>());
myList.get(0).add("rabbit");
myList.get(0).add("horse");
Here you have a list of your chained strings in some index and you can get them by accessing that item.
Upvotes: 0
Reputation: 3448
The way you showed is impossible. text[1] in your example is a reference to exatcly one String object, so you are overriding one reference (to rabbit) with a reference to another String (horse).
Storing two Strings in objects[0]:
Object[] objects = new Object[]{new String[]{"a","b"}, null, null};
Storing two references as two consecutive fields in an array (one object is referenced several array indexes):
Object o = new String("a");
objects[1] = o;
objects[2] = o;
Another solution for you:
Object[] text = new Object[]{new ArrayList<String>(), null, null};
text[0].add("rabbit");
text[0].add("horse");
Upvotes: 1
Reputation: 2208
No it is not possible to hv multipl ibjects on same index. Second is possible.
Upvotes: 0
Reputation: 989
First one you can do with 2 dimensional array like [][] array of string array Second one you can do.just an info, Strings are immutable object once you change they become another object
Upvotes: 0