Sobes.tech
Junior — Middle

Kas Java-s saab kasutada kogumit erinevat tüüpi elementide salvestamiseks?

sobes.tech AI

Vastus AI-lt

In Java, collections are usually parameterized with the element type (generics), for example, List<String> stores only strings. However, it is possible to use a collection with the type Object to store elements of different types:

List<Object> mixedList = new ArrayList<>();
mixedList.add("string");
mixedList.add(123);
mixedList.add(new Person("Anna", 25));

But this approach reduces type safety and requires explicit casting when retrieving elements. Therefore, it is recommended to use collections with a specific type, and for storing different types — create generic classes or use interfaces/abstract classes that unify these types.