Managing collections
In this section, we will review how collection objects can be created and initialized, what immutable collections are, and how to perform basic operations over collections—copy, sort, and shuffle, for example.
Initializing collections
We have already seen a few examples of collection constructors without parameters. Now, we are going to see other ways to create and initialize collection objects.
Collection constructor
Each of the collection classes has a constructor that accepts a collection of elements of the same type. For example, here is how an object of class ArrayList
can be created using the ArrayList(Collection collection)
constructor and how an object of class HashSet
can be created using the HashSet<Collection collection)
constructor:
List<String> list1 = new ArrayList<>(); list1.add("s1"); list1.add("s1"); List<String> list2 = new ArrayList<>(list1); System.out.println(list2); //prints: [s1, s1] Set<String> set = new HashSet...