What is the advantage of such a record:

Collection collection = new ArrayList(); 

before this:

 ArrayList collection = new ArrayList(); 

After all, we lose the unique methods of ArrayList in the 1st version?

    1 answer 1

    After all, we lose the unique methods of ArrayList in the 1st version?

    No, you do not lose. In both cases, you create an ArrayList object. The difference is that using the 1st option you can do this:

     collection = new LinkedList(); collection = new HashSet(); 

    etc (that is, if in the future you realize that the order of the elements is not important to you and, therefore, you want to use HashSet instead of ArrayList you will need to change less code). More specifically, in the 1st version you indicate that the variable named collection is of type Collection . Since Collection is an interface that all collections implement, you can refer to any collection.

    • Understood, we can change the type of collection if necessary, thanks for the reply - Andrei Kozitsky
    • @AndreyKozitsky, if the answer helped you, mark it as a solution . - Sergey Gornostaev