Java collection parameters

Question:

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:

quizful.net/post/Java-Collections – About Collections in Java. quizful.net/post/java-generics-tutorial – 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 docs.oracle.com/javase/8/docs/api/java/util/List.html ). 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. ( arininav.ru/js/java04.htm see paragraphs 5.4.1.3. and 5.4.1.4. )

Scroll to Top