Java – how to create an ArrayList correctly?

See English answers > type list vs type ArrayList in java15

List<String/*or other object*/> arrList = new ArrayList();//Imports List,ArrayList
ArrayList<String/*or other object*/> arrList = new ArrayList();//Imports just ArrayList

Any difference? Which method should be used?

Solution

The first form is recommended for the public interface of a class (for example, the declaration of attributes in a class) This is a well-known suggestion. You should program for an interface rather than a specific implementation (which is described in design patterns) – the number of classes you must import has little to do with the quality of code and good design

The advantage of the first form is that it will allow you to easily exchange implementations later if needed - while the second implementation, combined with implementation classes, makes your code more difficult to develop and less flexible

In some cases, specific classes can be declared and used (for example, slightly improved performance) However, the public interface of the class should use the interface as much as possible, which will make future changes easier to implement

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>