Why calling methods from container class instead of instances of it in Java

Mert Beşiktepe :

I am trying to learn java collections. But there is a particular syntax that i can't understand about calling collection methods. Like .toString() or .sort() e. g. ;

I don't understand the reason why we are calling the below methods from Arrays class or Collections class. For printing arrays this is called inside a println().

Arrays.toString(myArray);

For sorting lists

Collections.sort(myList);

And why not ?

myArray.toString();

myList.sort();

Can any one walk me through it?

Adam Millerchip :

From the first line of the docs:

The collections framework is a unified architecture for representing and manipulating collections, enabling them to be manipulated independently of the details of their representation. It reduces programming effort while increasing performance. It enables interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software reuse. The framework is based on more than a dozen collection interfaces. It includes implementations of these interfaces and algorithms to manipulate them.

The objective is to reduce code duplication. In the case of myList.sort(), all implementations of the List interface would have to implement the sort function, and each implementation's sort may vary in behaviour. But as a static method on the Collections class, List implementations do not need to implement the sort function. From a user's perspective, you can pass whatever List you have to Collections.sort() and know what is going to happen.

Since Java 8, this functionality could have been implemented with default methods, which is what List.sort(comparator) does. Default methods allow all implementations an interface to receive the implementation defined in the interface, so from Java 8 it is possible to do do myList.sort(), with the caveat that you have to tell it how to sort by providing a comparison function. For example, assuming you have a List<Integer>: mylist.sort(Integer::compareTo). But the Collections Framework pre-dates default methods, hence the need for Collections.sort().

As well as Collections.sort() and List.sort(comparator), you can also use Stream.sorted(): myList.stream().sorted().collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77951&siteId=1
Recommended