java - How to create ArrayList properly? -
this question has answer here:
- type list vs type arraylist in java 14 answers
below 2 ways how create arraylist
:
list<string/*or other object*/> arrlist = new arraylist();//imports list, arraylist arraylist<string/*or other object*/> arrlist = new arraylist();//imports arraylist
what difference? method should used?
the first form recommended for public interface of class (say, declaration of attributes in class). it's well-known advice should program interface, not concrete implementation (this stated in design patterns) - number of classes have import has little quality of code , design.
the advantage of first form it'll allow swap implementations later on, if need arises - whereas second implementation sets in stone implementing class, making code harder evolve , less flexible.
there cases when it's ok declare , use concrete classes, though (for instance, little bump in performance). public interface of class should use interfaces whenever possible, it'll make future changes easier implement.
Comments
Post a Comment