On Feb 12, 2010, at 11:05 AM, Florene Quan wrote:

> Can someone explain the difference between the following two declaration/instantiation of an ArrayList. > List<Integer> myNumbers = new ArrayList<Integer>(); and
> ArrayList<Integer> myNumbers = new ArrayList<Integer>();
>
> I understand that List is an interface and ArrayList is the data structure that implements that interface.
>
> Is there a real difference between the two ArrayList statements?  Is it sufficient if students just accept it as a syntax thing or is a further explanation needed? I am not sure what the difference is and how to explain it to students.
>
>
> What about this declaration.
>
> List<Integer> myLinkedList  = new LinkedList<Integer>();
>
> It means myLinkedList and and myNumbers share the same behavior. Is there any more to it that that?

There is an important difference.  Suppose that you want to pass myNumbers as an argument to a method, store a reference to it in a variable, etc.  If you are using the second form the natural thing to do is to declare the parameter and the variable as type ArrayList<Integer>.  But if you then wanted to change your program so that myNumbers was a LinkedList<Integer> you would have to find and change all of those declarations of variables and parameters.

Let's do this again, declaring myNumbers and any parameters or variables related to myNumbers as type List<Integer>.  In that case, changing your program so that myNumbers is a LinkedList<Integer> would require exactly one change.  The original declaration would change from:

  List<Integer> myNumbers = new ArrayList<Integer>();

to

  List<Integer> myNumbers = new LinkedList<Integer>();

And if you later wanted to create a List using a different data structure, you could call that class MyList and have it implement List.  Then you could say:

  List<Integer> myNumbers = new MyList<Integer>();

and the rest of the program would be unchanged.

By declaring variables and parameters of type List<Integer> you are hiding which implementation of the List interface you are using.  Therefore any class that implements the List interface could be used, and the program will continue to work correctly (although it might be faster for some implementations than for others, which is a good reason to have multiple implementations).

The bottom line - if all the methods that your program needs are specified in an interface, declare all variables and parameters using the interface type rather than the type of a specific implementation of the interface.  This will give your program maximum flexibility to later change the data structures it uses.

Scot Drysdale
====
Course related websites:
http://apcentral.collegeboard.com/compscia
http://apcentral.collegeboard.com/compsciab
---
To unsubscribe click here:
 http://lyris.collegeboard.com/read/my_forums/?forum=
To change your subscription address or other settings click here:
 http://lyris.collegeboard.com/read/my_account/edit