Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Collections class contain standalone (static) methods, instead of them being added to the List interface?

For all the methods in Collections that take a List as their first argument, why aren't those methods simply part of the List interface?

My intuition is: given a List object, that object itself should "know" how to perform on itself operations such as rotate(), shuffle(), or reverse(). But instead, as a Java programmer, I have to review both the methods in the List interface, as well as the static methods "over there" in the Collections class, to ensure I'm using a canonical solution.

Why were some methods placed as static standalone methods in the Collections class, instead of being added to the List interface (and presumably thus implemented by some existing or would-be base class)?

I'm trying to better understand the design decisions behind the Java collections framework.

Is there some compelling OO design principle here that I'm overlooking? Or was this distinction done simply for some practical, performance reason?

like image 688
Aaron Fi Avatar asked Jun 21 '10 23:06

Aaron Fi


People also ask

Why do we need static method in interface?

Java interface static method helps us in providing security by not allowing implementation classes to override them. We can't define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”.

What is the purpose of static methods?

A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

When should you use a static method when you want your method to be available?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.


1 Answers

The point is that given suitable primitive operations (remove, set etc) a bunch of more high level operations (sort, shuffle, binary search) can be implemented once rather than being implemented by every single list implementation.

Effectively, java.util.Collections is like .NET's Enumerable class - full of general purpose methods which can work on any collection, so that they can share a single implementation and avoid duplication.

like image 61
Jon Skeet Avatar answered Oct 07 '22 00:10

Jon Skeet