1

Can someone explain the following code to me. As in why is "List" and "ArrayList" are not the same? Does this mean that the variable neighborColumns is a List data structure that holds type Column objects but only public methods from class List can be used on variable neighborColumns? thanks in advance.

List<Column> neighborColumns = new ArrayList<Column>();

2 Answers 2

3

This code is ok (Design to interface (List): -

List<Column> neighborColumns = new ArrayList<Column>();
List<Column> neighborColumns = new LinkedList<Column>();   // OK To change..

In the above code, you are basically designing to an interface rather than implementation..List is an interface and ArrayList is a concrete class implementing it.

An advantage is that, you can switch between various implementation, without changing the design..

Below code is a problem (Design to implementation (ArrayList):-

ArrayList<Column> neighborColumns = new ArrayList<Column>();

//OOPs.. Cry (Incompatible Types)
ArrayList<Column> neighborColumns = new LinkedList<Column>(); 

Here since you are designing to an implementation.. So you can not change the implementation on the RHS.. The compiler will cry as above..

So, in general also, you should always design to an interface, thus not exposing the implementation, and also gaining flexibility of changing the implementation anytime..

Sign up to request clarification or add additional context in comments.

4 Comments

when you say changing the implementation do you mean that I can add new methods to the concrete class that in this case is ArrayList or I am completely misunderstanding you?
@12345.. No changing the implementation means, making your list point to a different class objects.
So would I be able to make changes like the following?
@12345.. Yeah of course.. You should write your code like this only..See my edit..
1

List is an interface while ArrayList is a specific class that implements that interface.

It is a good programming practice to program against interfaces rather than specific classes where possible, because it makes it easier to change to using a different list implementation later.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.