Java: how can I create a dynamic array without forcing a value type?

I need to create a dynamic array in Java, but the type of the values ​​is different from String to Int to float. How can I create a dynamic list that I do not need to give in the extended value type?

Keys just have to be incremental (1,2,3,4 or 0,1,2,3,4)

I checked the ArrayList, but it seems that I should give it a fixed type for the values.

thanks!

+4
source share
4 answers

You can have an array or ArrayList Objects that allows you to contain String , int , and float .

+4
source

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); 
+2
source

Quite rarely, in my experience, I want a List<Object> . I think it might be a designer smell, and I will look at the design to see if another set of structures can better represent your data. Without knowing anything about what you are trying to solve, it’s hard to say with certainty, but as a rule, everyone wants to do something with what is listed and do something meaningful in things when they are just Object , you will need to study their type and get reflexivity in order to distract from the language basics. Unlike storing them in more type-sensitive structures, where you can directly access them in your original types without reflection magic.

+2
source

This is more of a problem than it's worth, but reflexivity with arrays can be reflected.

 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" } 

References

Note that in the API you pass arrays as Object . This is because Object is a superclass of all types of arrays, be it int[].class or String[][].class . It also means that there is little compile-time security (as is true with reflection in general). Array.getLength("mamamia") compiles just fine; it will throw an IllegalArgumentException at runtime.

+1
source

Source: https://habr.com/ru/post/1306480/


All Articles