Junior — Middle
How to implement a list capable of containing objects of different types without using generics?
sobes.tech AI
Answer from AI
To create a list capable of containing objects of various types without using generics, you can use the base class Object in Java or Kotlin. Since all classes inherit from Object, a list of type List<Object> can store any objects.
Example in Java:
List<Object> mixedList = new ArrayList<>();
mixedList.add("String");
mixedList.add(123); // Integer
mixedList.add(new CustomClass());
When retrieving elements, you will need to cast them to the appropriate type, which requires caution and type checking with instanceof.
This solution is suitable if generics cannot be used, but it requires additional type handling when working with list elements.