为什么 List 中没有 tail() 或 head() 方法来获取最后一个或第一个元素? [英] Why no tail() or head() method in List to get last or first element?
问题描述
我最近和一位同事讨论了为什么 Java 中的 List 接口没有 head()
和 tail()
方法.
I recently had a discussion with a collegue why the List interface in Java doesn't have a head()
and tail()
method.
为了实现这样的功能,必须编写一个看起来像这样的包装器:
In order to implement such a functionality would have to write a wrapper that looked something like this:
public E head() {
if (underlyingList == null || underlyingList.isEmpty())
return null;
return underlyingList.get(0);
}
public E tail() {
if (underlyingList == null || underlyingList.isEmpty())
return null;
return underlyingList.get(underlyingList.size()-1);
}
我不了解所有 List 实现,但我认为至少在 LinkedList 和 ArrayList 中,获取最后一个和第一个元素(恒定时间)应该非常简单.
I'm not aware of all List implementations but I assume that at least in LinkedList and ArrayList it should be pretty trivial to get the last and first element (constant time).
所以问题是:
为任何 List 实现提供尾部方法不是一个好主意有什么具体原因吗?
Is there a specific reason why it is not a good idea to provide a tail method to any List implementation?
推荐答案
Java Collections Framework 由 Joshua Bloch 编写.他的 API 设计原则之一是:高功率重量比.
Java Collections Framework is written by Joshua Bloch. One of his API design principles is: High power-to-weight ratio.
tail()
和 head()
可以通过 get()
和 size()
实现,所以没有必要将 tail()
和 head()
添加到非常通用的接口 java.util.List
中.一旦用户使用了这些方法,您就没有机会删除它们,您必须永远维护这些不必要的方法.这很糟糕.
tail()
and head()
can be implemented by get()
and size()
, so it's not necessary to add tail()
and head()
to a very general interface java.util.List
. Once users use the methods, you don't have chance to remove them and you have to maintain these unnecessary methods forever. That's bad.
这篇关于为什么 List 中没有 tail() 或 head() 方法来获取最后一个或第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!