为什么Collections类包含独立(静态)方法,而不是将它们添加到List接口? [英] Why does the Collections class contain standalone (static) methods, instead of them being added to the List interface?

查看:183
本文介绍了为什么Collections类包含独立(静态)方法,而不是将它们添加到List接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

集合将列表作为第一个参数,为什么这些方法不是List接口的一部分?



我的直觉是:给定一个List对象,该对象本身应该知道本身的操作,如rotate(),shuffle()或reverse()。但是,作为一个Java程序员,我必须检查List接口中的方法,以及Collections类中的over there的静态方法,以确保我使用规范的解决方案。



为什么一些方法作为静态独立方法放置在Collections类中,而不是添加到List接口(并且可能是由一些现有或将来的基类实现)?

我想更好地了解Java集合框架背后的设计决策。



有一些引人注目的OO设计原则在这里,我忽略?

解决方案

关键是给定合适的原始操作(remove,set等等),一系列更高级的操作(排序,随机,二进制搜索)可以被实现一次,而不是由每个列表实现实现。



有效地,java.util.Collections类似于.NET的Enumerable类 - 充满了通用目的的方法,可以在任何集合上工作,以便他们可以共享单个实现,避免重复。


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?

解决方案

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.

这篇关于为什么Collections类包含独立(静态)方法,而不是将它们添加到List接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆