Use interface or type for variable definition in java? -
arraylist alist = new arraylist(); list alist = new arraylist();
what's difference between these 2 , better use , why?
list<t>
interface, arraylist<t>
class, , class implements list<t>
interface.
i prefer 2nd form, more general, ie if not use methods specific arraylist<t>
can declare type interface list<t>
type. 2nd form easier change implementation arraylist<t>
other class implements list<t>
interface.
edit: many of users commented both forms can arguments method accept list<t>
or arrraylist<t>
. when declare method prefer interface:
void showall(list <string> sl) ...
and use:
void showallas(arraylist <string> sl) ...
only when method uses method specific arraylist<t>
, ensurecapacity()
.
response information should use typed list<t>
instead of list
(of course if not use ancient java).
Comments
Post a Comment