Collections class in Java consists only from static methods, as stated in the specs
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
The class has private constructor, however it is not marked as final
. Aren't there any performance benefits if the class would be final itself? What's the reason behind this?
2 Answers 2
Aren't there any performance benefits if the class would be final itself?
For instance methods, potentially. For static methods, no. Knowing that a non-overridden instance method is in a final
class would potentially allow the method to be statically bound when called, rather than going through virtual dispatch, but static
methods are already statically bound. It doesn't matter whether the class defining the static
method is final
or not, the call must be bound statically for all static
methods.
-
2That's a nice way to remember it, but it is not the actual reason for the name.Sebastian Redl– Sebastian Redl2016年09月28日 17:05:14 +00:00Commented Sep 28, 2016 at 17:05
-
2@SebastianRedl, Servy is not claiming anything about the actual reason for the name. However, feel free to enlighten us, since you've broached the subject: what is the actual reason for the name?Erik Eidt– Erik Eidt2016年09月28日 19:20:39 +00:00Commented Sep 28, 2016 at 19:20
-
1I interpret "hence the name" as "that's that reason for the name". Anyway, the name derives from C's static local variables (same as in Java), which have static existence (as opposed to the dynamic existence of normal variables). The keyword was reused by C++ to denote member variables that are not bound to one instance, and then by Java for the same purpose.Sebastian Redl– Sebastian Redl2016年09月28日 20:34:54 +00:00Commented Sep 28, 2016 at 20:34
-
@SebastianRedl Yep exactly. Under the covers, C++ static data is just like C static data, and "static" acquired the association of representing class-scoped members.SusanW– SusanW2016年10月18日 18:06:26 +00:00Commented Oct 18, 2016 at 18:06
The constructor for Collections is private so there is no way to extend it. And as noted in the answer by Servy, these methods are not polymorphic so whether it is final is not relevant to performance. Marking it final has no impact so adding that is superfluous. Whether it was left of for that reason or just not considered is unclear.
final
for performance reasons. It's used to indicate the class is not meant to be extended. This class is obviously not meant to be extended, but who knows why it wasn't declaredfinal
? Maybe ask Josh Bloch? :)