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

Popular posts from this blog

ruby - When to use an ORM (Sequel, Datamapper, AR, etc.) vs. pure SQL for querying -

php - PHPDoc: @return void necessary? -

c++ - Convert big endian to little endian when reading from a binary file -