Java collection parameters


I come across various options for declaring collections:

List<Integer> list = new ArrayList<Integer>(); //1

List list = new ArrayList<Integer>(); // 2

List<Integer> list = new ArrayList(); //3  

And there is absolutely no clarity about which objects can be put into which collection. Experimentally found out that in collection 2 – you can add objects (Object). And in collection 3 – only with the Integer type.

Question 1: how to understand from the declaration which objects a collection can contain?

Question 2: For what applications can you use the first, second and third options for declaring collections?

Answer: – About Collections in Java. – Generics. The key to understanding collections.

On question 1: The type in the angle brackets <> should be for objects that the collection can contain.

On question 2: 1 and 3 – we use it when it is necessary to store an array of integers that is variable in capacity. 2 – when you need to operate with collections that can contain different types of data. Those. we can under list have both a collection of integers and a collection of strings or a collection of collections. I recommend reading about interfaces (in OOP or in Java in particular) first of all. And about the model of data organization in computer memory.

In short, all classes in Java are inheritors of the Object class. The List interface is defined as public interface List<E> extends Collection<E> (see ). A List list declaration can be read as List<Object> list . Accordingly, since a list can contain any objects that extend a class that a collection can contain, then we can place an object of a list of objects of any class under the list link. ( see paragraphs and )

Scroll to Top