list interface implementation class distinction arraylist

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

 

The first form of this class as a reference type, then the method of access to all public ArrayList this class. The second form, using the Interface List ArrayList implemented as a reference type, then the reference list can be accessed by a method defined in the interface. That ArrayList class implements the List interface, in addition to the method must implement the interface List declared, some additional methods can also be achieved. However, methods other than the second form of the List interface can not be called.
Use, design mode are: "Code possible depends on the abstract, is not dependent on the specific." The first form is dependent on specific, the second form is dependent on the abstract. Because the List is the interface. Code relies on abstract advantage is that the code can be easily replaced. For example, Code List list = new ArrayList (); operated by a set of the following list. After writing the code found inaccurate use of the set, you should use LinkedList, then simply change one line of code List list = new LinkedList (); it can, after this line of code does not need to be modified because the List interface ensures that calls are the interface methods, and ArrayList and LinkedList implement the List interface. And if at the time with ArrayList list = new ArrayList () This form, then access to the list, it could be a unique method in ArrayList method List interface instead. Such replaced LinkedList when there may need to modify a lot of code.

Guess you like

Origin www.cnblogs.com/mike-JP/p/10993088.html