Type List vs type ArrayList in Java

2018-12-31 03:36发布

(1) List<?> myList = new ArrayList<?>();

(2) ArrayList<?> myList = new ArrayList<?>();

I understand that with (1), implementations of the List interface can be swapped. It seems that (1) is typically used in an application regardless of need (myself I always use this).

I am wondering if anyone uses (2)?

Also, how often (and can I please get an example) does the situation actually require using (1) over (2) (i.e. where (2) wouldn't suffice..aside coding to interfaces and best practices etc.)

15条回答
路过你的时光
2楼-- · 2018-12-31 04:00

(3) Collection myCollection = new ArrayList();

I am using this typically. And only if I need List methods, I will use List. Same with ArrayList. You always can switch to more "narrow" interface, but you can't switch to more "wide".

查看更多
情到深处是孤独
3楼-- · 2018-12-31 04:01

The only case that I am aware of where (2) can be better is when using GWT, because it reduces application footprint (not my idea, but the google web toolkit team says so). But for regular java running inside the JVM (1) is probably always better.

查看更多
皆成旧梦
4楼-- · 2018-12-31 04:02

List interface have several different classes - ArrayList and LinkedList. LinkedList is used to create an indexed collections and ArrayList - to create sorted lists. So, you can use any of it in your arguments, but you can allow others developers who use your code, library, etc. to use different types of lists, not only which you use, so, in this method

ArrayList<Object> myMethod (ArrayList<Object> input) {
   // body
}

you can use it only with ArrayList, not LinkedList, but you can allow to use any of List classes on other places where it method is using, it's just your choise, so using an interface can allow it:

List<Object> myMethod (List<Object> input) {
   // body
}

In this method arguments you can use any of List classes which you want to use:

List<Object> list = new ArrayList<Object> ();

list.add ("string");

myMethod (list);

CONCLUSION:

Use the interfaces everywhere when it possible, don't restrict you or others to use different methods which they want to use.

查看更多
登录 后发表回答