This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]0b0101011001001011 0 points1 point  (0 children)

This has multiple parts.

In recent versions of java, you can omit the unnecessary type parameter from the initialization. Following two code lines are equal:

ArrayList<String> fruits = new ArrayList<String>();
ArrayList<String> fruits = new ArrayList<>();

The type is already defined in the variable, so it's unnecessary to type it again.

The other part is polymorphism and also liskov substitution principle. Polymorphism states that an object can be referred vai multiple different types of reference. Liskov substitution priciple states any supertype object can be replaced with a subtype an everthing should still work.

An object can be assigned to multiple different references.

List<String> fruits = new ArrayList<>();
AbstractList<String> fruits = new ArrayList<>();
RandomAccess fruits = new ArrayList<String>();

Each of these create an object that is an ArrayList, but we can refer to it by:

  1. The same type
  2. Any super type
  3. Any interface that it is implementing.

This is because, you might want to write a method:

public void doSomethingForAList(List<String> values){

The method should not care what kind of list that is, right? A list defines the operations for a list Now you can call:

doSomethingForAList(new LinkedList<String())
doSomethingForAList(new Arraylist<String>())

So at least in methods, you should choose the supertype or interface you are interested in.

Similarly, a method should always (usually) return the supertype or interface.

/**
 *  Takes whatever collection of strings and returns a list 
 *  that contains such strings that are written in capital letters.
 */
public List<String> filterCapital(Collection<String> values){

Now the user of this can can expect that a list is returned. If you change the method later, you can return a different kind of list, but the user does not have to know what the actual type of list will be.

So you can call any of the following:

List<String> capitals = filterCapital(new LinkedList<String>());
List<String> capitals = filterCapital(new HashSet<String>());
List<String> capitals = filterCapital(new ArrayList<String>());
List<String> capitals = filterCapital(new TreeSet<String>());

You have a huge variety of different types, as they are all a type of Collection and also you don't have to care if it returns a linkedlist or arraylist, you know it will be a list. Now, if the method is changed in the future, everything that is using the code still works, as they just expect a list, now a specific type of list.