Hello! Over the past few lessons, we have made great progress in mastering ArrayList. However, during this time we performed only the simplest operations: deleting, inserting, outputting to the console. Of course, this is not the end of the list of problems that developers face when using ArrayList . Remember the lecture about arrays and the Arrays class ? It was developed by the creators of Java specifically to solve common problems that programmers encounter when working with arrays. What about ArrayList ? Surely there is some list of typical tasks for him too. Were they all implemented in some separate class, or will we have to write the desired behavior manually each time? Of course, you don’t need to write everything yourself. The most common operations that are performed when using collections in Java have already been implemented in a special static class Collections.
Collections in Java
“Collections” is a generic name for several data structures in Java. Data can be stored in many different ways. So far we have only studied the ArrayList class , where data is stored in an array. We will get acquainted with the rest of the collections later. Now it is enough to understand that the Collections class is designed to work not only with ArrayList, but also with other types of collections in Java (hence, in fact, its name). So, what tasks does the Collections class allow you to solve when working with ArrayList? The first and most obvious is sorting. In the lecture on arrays, we looked at an example with numbers, and now let's look at an example with strings. To sort the contents of collections, the Collections class implements the following methodsort()
:
public class Main {
public static void main(java.lang.String[] args) {
String mercury = new String("Mercury");
String venus = new String("Venus");
String earth = new String("Earth");
String mars = new String("Mars");
String jupiter = new String("Jupiter");
String saturn = new String("Saturn");
String uranus = new String("Uranus");
String neptune = new String("Neptune");
ArrayList<String> solarSystem = new ArrayList<>(Arrays.asList(mercury, venus, earth, mars,
jupiter, saturn, uranus, neptune));
Collections.sort(solarSystem);
System.out.println(solarSystem);
}
}
Conclusion:
[Венера, Земля, Марс, Меркурий, Нептун, Сатурн, Уран, Юпитер]
The lines have been sorted alphabetically! Why in alphabetical order? The class String
is programmed to determine exactly how strings are compared with each other (precisely alphabetically). For classes that you will create yourself, you can implement your own comparison mechanism, but we will talk about this in other lectures. Additionally, the Collections class allows you to find the minimum and maximum element in a ArrayList
. This is done using the min()
and methods max()
:
public static void main(java.lang.String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
System.out.println(Collections.max(numbers));
System.out.println(Collections.min(numbers));
}
Conclusion:
7
1
This, of course, is much more convenient than manually writing code to go through all the elements and search for the largest/smallest element :) Another extremely useful method is reverse()
. If we needed to “reverse” a list so that the elements were in reverse order, how would we do it? It would probably not be so easy to write such an algorithm yourself :) Fortunately, the method reverse()
already knows how to do this. For example, we don't like how the method sort()
sorted our planets in alphabetical order, and we want to change the order to the reverse - from Z to A:
public class Main {
public static void main(java.lang.String[] args) {
String mercury = new String("Mercury");
String venus = new String("Venus");
String earth = new String("Earth");
String mars = new String("Mars");
String jupiter = new String("Jupiter");
String saturn = new String("Saturn");
String uranus = new String("Uranus");
String neptune = new String("Neptune");
ArrayList<String> solarSystem = new ArrayList<>(Arrays.asList(mercury, venus, earth, mars,
jupiter, saturn, uranus, neptune));
Collections.sort(solarSystem);
Collections.reverse(solarSystem);
System.out.println(solarSystem);
}
}
Conclusion:
[Юпитер, Уран, Сатурн, Нептун, Меркурий, Марс, Земля, Венера]
By the way, here we often talk about sorting, order of elements, etc. What if our task is exactly the opposite? For example, we are trying to implement a lottery mechanism. We have added 100 numbers to the reel, which should appear on the screen one at a time. The first participant to cross out all the numbers on their ticket wins. It is very easy to implement such a mechanism using the method shuffle()
:
public class Main {
public static void main(java.lang.String[] args) {
ArrayList<Integer> lottery = new ArrayList<>(100);
for (int i = 1; i <= 100; i++) {
lottery.add(i);//add numbers from 1 to 100 to the drum
}
Collections.shuffle(lottery);//mix
System.out.println("Attention! The first 10 numbers appear from the drum!");
for (int i = 0; i < 10; i++) {
System.out.println(lottery.get(i));
}
}
}
Conclusion:
Внимание! Из барабана появляются первые 10 чисел!
32
61
4
81
25
8
66
35
42
71
It's that simple! The problem is solved, and our piece of the game is written :) Now let's imagine a different situation. Previously, we created a list solarSystem
with the planets listed in it. And it seems to suit us all, if not for one thing: you can remove elements from it and add new ones! This is clearly not the behavior we expect: the solar system in our program should be in an unchanged state. The Collections class has a very interesting method - unmodifiableList()
. It creates an immutable version of the given list. It will be impossible to add or remove an element to it. In the case of the list of planets of the solar system, this is exactly what we need!
public class Main {
public static void main(java.lang.String[] args) {
String mercury = new String("Mercury");
String venus = new String("Venus");
String earth = new String("Earth");
String mars = new String("Mars");
String jupiter = new String("Jupiter");
String saturn = new String("Saturn");
String uranus = new String("Uranus");
String neptune = new String("Neptune");
List<String> solarSystem = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(mercury, venus, earth, mars,
jupiter, saturn, uranus, neptune)));
solarSystem.add("Pluto");//try to add a new element
}
}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1075)
at Main.main(Main.java:21)
Error: solarSystem
Now you can't add anything! The only thing you need to pay attention to in this case is that the type of the variable must be List<>
, and not ArrayList<>
(this method returns an object of exactly this type, common to all types of lists). Another common situation that can happen during work is that the programmer added elements in the wrong order. If this happened, and Mercury and Neptune unexpectedly changed places, the following method will help us correct this mistake swap()
:
public class Main {
public static void main(java.lang.String[] args) {
String mercury = new String("Mercury");
String venus = new String("Venus");
String earth = new String("Earth");
String mars = new String("Mars");
String jupiter = new String("Jupiter");
String saturn = new String("Saturn");
String uranus = new String("Uranus");
String neptune = new String("Neptune");
ArrayList<String> solarSystem = new ArrayList<>(Arrays.asList(neptune, venus, earth, mars
, jupiter, saturn, uranus, mercury));// wrong planet order
System.out.println(solarSystem);
Collections.swap(solarSystem, solarSystem.indexOf(mercury), solarSystem.indexOf(neptune));
System.out.println(solarSystem);
}
}
We passed our list to the method swap()
, as well as the indices of the two elements that need to be swapped. Please note: the method works specifically with indexes, and not with links. Therefore, here we needed a method ArrayList.indexOf()
. Conclusion:
[Нептун, Венера, Земля, Марс, Юпитер, Сатурн, Уран, Меркурий]
[Меркурий, Венера, Земля, Марс, Юпитер, Сатурн, Уран, Нептун]
Finally, let's get acquainted with a very interesting method - disjoint()
. It checks whether two collections have intersections, that is, at least one identical element. If not, returns true
, if yes, returns false
.
public class Main {
public static void main(java.lang.String[] args) {
String mercury = new String("Mercury");
String venus = new String("Venus");
String earth = new String("Earth");
String mars = new String("Mars");
String jupiter = new String("Jupiter");
String saturn = new String("Saturn");
String uranus = new String("Uranus");
String neptune = new String("Neptune");
ArrayList<String> solarSystemPart1 = new ArrayList<>(Arrays.asList(mercury, venus, earth, mars));
ArrayList<String> solarSystemPart2 = new ArrayList<>(Arrays.asList(jupiter, saturn, uranus, neptune));
System.out.println(Collections.disjoint(solarSystemPart1, solarSystemPart2));
}
}
As you can see, the elements in our two lists are completely different, so the program outputs true
. This is such an interesting and very useful class. Like Arrays
, he does a lot of routine, menial work for us, allowing us to focus on other things. Read about it in the Oracle documentation , there are other methods there.
GO TO FULL VERSION