当它由ArrayList类而不是接口List表示时,是不是更容易使用foo? [英] Isn't it easier to work with foo when it is represented by the class ArrayList rather than the interface List?

查看:99
本文介绍了当它由ArrayList类而不是接口List表示时,是不是更容易使用foo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个语法很多,不明白背后的推理。我认为你一般都希望使用类而不是接口来更容易地执行你可能想要执行的操作的全部。

I see this syntax a lot and don't understand the reasoning behind it. I thought you generally want to work with classes rather than interfaces to make it easier to carry out the full panoply of operations you might want to perform.

为什么这样做: / p>

Why do this:

List<Foo> foo = new ArrayList<Foo>(something.getFoo());

而不是这样:

ArrayList<Foo> foo = new ArrayList<Foo>(something.getFoo());

如果foo由类ArrayList而不是接口List来表示,这不是很容易吗?

when you later want to perform operations on foo? Isn't it easier if foo is represented by the class ArrayList rather than the interface List?

推荐答案

偶尔,是的。如果您实际上需要 ArrayList 中声明的方法,但不在列表中< T> 然后肯定,去吧。

Occasionally, yes. If you actually need a method that's declared in ArrayList<T> but not in List<T> then sure, go for it.

但是,相反的是更灵活 - 如果你不需要 ArrayList< T> ,那么您的代码可以通过将变量声明为 List< T> 。这就是说,我只是需要一个列表,我碰巧选择 ArrayList< T> ,但只是因为它的行为适合我...不是因为我需要任何额外的功能它暴露。

However, the reverse is more flexible - if you don't need any methods declared in ArrayList<T>, then your code can express that by declaring the variable to be of type List<T> instead. That says, "I just need a list. I happen to be picking ArrayList<T>, but just because its behaviour suits me... not because I need any extra features it exposes."

这很有用,知道以后有人想知道他们是否可以替换不同的实现,例如。它也限制了读者必须考虑多少...变量的类型越多,用户可以做的就越少 - 因此需要考虑的变量越少。

That's useful to know if later someone wonders whether they could substitute a different implementation, for example. It also limits how much a reader has to think about... the more general the type of the variable, the less one can do with it - so the less one needs to think about it.

例如,如果我看到类型 Iterable< T> 的变量,我知道有很多宝贵的东西可能在以后完成:基本上,将被用于迭代,这就是所有。我不需要担心是否有任何后来的代码试图添加一个值到集合,或通过索引等访问它。

For example, if I see a variable of type Iterable<T> I know there's precious little that's likely to be done with it later: basically, it's going to be used to iterate, and that's all. I don't need to worry about whether any later code is going to try to add a value to the collection, or access it by index etc.

这是相对对于局部变量不重要,但是对于实例变量和特别是参数来说更是如此:您作为参数的具体性越小,调用者对它们将传递哪些参数越灵活。

This is relatively unimportant for local variables, but much more so for instance variables and particularly parameters: the less concrete you make your parameters, the more flexibility the caller has about which arguments they'll pass.

这篇关于当它由ArrayList类而不是接口List表示时,是不是更容易使用foo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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