在java中使用接口或类型进行变量定义? [英] Use interface or type for variable definition in java?

查看:172
本文介绍了在java中使用接口或类型进行变量定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayList aList = new ArrayList();

List aList = new ArrayList();

这两者之间有什么区别,哪个更好用,为什么?

What's the difference between these two and which is better to use and why?

推荐答案

列表< T> 是接口,其中 ArrayList< T> 是类,此类实现 List< T> interface。

List<T> is interface, where ArrayList<T> is class, and this class implements List<T> interface.

我会更喜欢第二种形式,这是更通用的,即如果你不使用特定于 ArrayList< T> 的方法,你可以将其类型声明为接口 List< T> 类型。使用第二种形式,可以更容易地将实现从 ArrayList< T> 更改为实现 List< T> 的其他类接口。

I would prefer 2nd form, which is more general, ie if you do not use methods specific to ArrayList<T> you can declare its type as interface List<T> type. With 2nd form it will be easier to change implementation from ArrayList<T> to other class that implements List<T> interface.

编辑:
由于许多SO用户都注释了这两种形式,因此可以接受任何接受<$ c $的方法c>列表< T> 或 ArrrayList< T> 。但是,当我声明方法时,我更喜欢接口:

As many of SO users commented both forms can be arguments to any method that accept List<T> or ArrrayList<T>. But when I declare method I would prefer interface:

 void showAll(List <String> sl) ...

并使用:

 void showAllAS(ArrayList <String> sl) ...

仅在我的方法使用时特定于 ArrayList< T> 的方法,如 ensureCapacity()

only when my method uses method specific to ArrayList<T>, like ensureCapacity().

我们应该使用键入列表< T> 而不仅仅是列表的信息响应非常好(当然,如果我们不使用古代Java)。

Response with information that we should use typed List<T> instead of just List is very good (of course if we do not use ancient Java).

这篇关于在java中使用接口或类型进行变量定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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