Reputation: 32104
I need to create a dynamic array in Java, but the values type differ from String to Int to float. how can I create a dynamic list that I don't need to give it in advanced the type of the values?
The keys just need to be ascending numbers (1,2,3,4 or 0,1,2,3,4)
I checked ArrayList but it seems that I have to give it a fixed type for the values.
thanks!
Upvotes: 5
Views: 6671
Reputation: 383746
It's more trouble than it's worth, but it is possible to interact with arrays reflectively.
import java.lang.reflect.Array;
// ...
Object arr = Array.newInstance(int.class, 10);
System.out.println(arr.getClass().getName()); // prints "[I"
System.out.println(Array.getLength(arr)); // prints "10"
Array.set(arr, 5, 42);
if (arr instanceof int[]) {
int[] nums = (int[]) arr;
System.out.println(nums[5]); // prints "42"
}
Do note that in the API you pass arrays as Object
. This is because Object
is the superclass of all array types, be it int[].class
or String[][].class
. This also means that there is little compile time safety (as is true with reflection in general). Array.getLength("mamamia")
compiles just fine; it'll throw an IllegalArgumentException
at runtime.
Upvotes: 1
Reputation: 40336
It's pretty rare, in my experience, to want a List<Object>
. I think it might be a design smell, and I'd examine the design to see if another set of structures might better represent your data. Without knowing anything about what you're trying to solve, it's hard to say with any confidence, but typically one wants to do things with what one has put into a list, and to do anything meaningful with things once they're just Object
, you'll need to examine their type and get reflective, to kind of break away from language basics. Versus storing them in more type-sensitive structures, where you can deal directly with them in their original types without reflection magic.
Upvotes: 2
Reputation: 72514
You can use this:
List<Object> myList = new ArrayList<Object>();
Integer i = 1;
Double d = 1.2;
String s = "Hello World";
myList.add(i);
myList.add(d);
myList.add(s);
Upvotes: 2
Reputation: 91786
You can have an array or an ArrayList
of Objects
which will allow you to contain String
, int
, and float
elements.
Upvotes: 4