From practice it is better to work with collections than with arrays. But specifically why it is not clear. Because collections are parameterized by objects, and not by primitives ?, so arrays can also have the type of added values, you can iterate through an array just like a collection, there are also Util classes for arrays and collections. The answer to the following questions is needed:

  • What collections are better than arrays?
  • What are the advantages of collections over arrays?
  • When is it better to use arrays than collections?

    2 answers 2

    It seems to me that you are confusing concepts. If array functionality is enough for you, then use it, no problems. But in the collections there are much more opportunities to find something really suitable for the tasks.

    The classic collection selection algorithm (for Java , there is no one on hand who has one, but the idea will not change because of this):

    enter image description here

    In this case, the arrays here are in the block array . vector is already a dynamic array closer to an ArrayList<> .

    Of course, any algorithm and any structure from the collections can be implemented by yourself, but why? ..

    Directly on issues:

    What collections are better than arrays?

    They have more functionality; doing this over arrays is often impractical (either the poor quality of the code is either long to implement or require a good understanding of the algorithms).

    When is it better to use arrays than collections?

    When you need to store a fixed-size data set. See the picture with the selection.

      Let's take it in order:

      1. What collections are better than arrays?

      If you are working with primitive types, and do not want to waste time on boxing/unboxing , then arrays are preferable. But if you use regular classes, it is better to use collections, because arrays are covariant. Those. it is easy to write non- type-safe code with them.

      For example, such:

        Integer[] a1 = new Integer[10]; Object[] a2 = a1; a2[0] = "привет ArrayStoreException!"; 

      At the same time, the compiler will never say that this is not correct.

      1. What are the advantages of collections over arrays?

      It all depends very much on your tasks. There are many different data structures in collections, with different properties. For example, Set is a set of unique elements, TreeSet is a set of unique sorted elements, List is a list that preserves the order of insertion, etc. You cannot give a definite answer here, rather a question about the expediency of its application. If at some point you don’t miss a simple array, feel free to use collection .

      1. When is it better to use arrays than collections?

      see point 2.