Last Updated on 11 April 2024   |   Print Email
This Java tutorial helps you understand the usage of the Collections utility class for ordering and manipulating elements in a List collection.The java.util.Collections class provides reusable functionalities that operation on collections such as changing the order of list elements and changing the content of a list. These are grouped into “generic algorithms” category. In this article, we help you understand how to use these functionalities with code examples.
You can use this method in conjunction with the subList() method to rotate only a range of elements in the list, while other elements remain unchanged. For example:
The following method sorts the specified list into ascending order, according to the natural ordering of its elements (all elements must implement the Comparableinterface):
public static void sort(List<T> list)
Note that the specified list must be modifiable, and the implementation in JDK uses mergesort algorithm.Code example:
The following method copies all of the elements from the source list (src) to the destination list (dest):
public static <T> void copy(List<? super T> dest, List<? extends T> src)
The copied elements replace the elements in the destination list at the same index. Note that the destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.Code example:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments