generic implementation for future flexibility

gudii9
gudii9 used Ask the Experts™
on
public class CollectionsRef {
 
    private HashSet<Integer> numbers;
 
    public ArrayList<String> getList() {
 
        return new ArrayList<String>();
    }
 
    public void setNumbers(HashSet<Integer> numbers) {
        this.numbers = numbers;
    }
}
Look at the reference types which are collection implementation classes - this locks the code to work with only these classes HashSet and ArrayList. What if we want the method getList() can return a LinkedList and the method setNumbers() can accept a TreeSet?
The above class can be improved by replace the class references to interface references like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class CollectionsRef {
 
    private Set<Integer> numbers;
 
    public List<String> getList() {
        // can return any kind of List
     [b]   return new ArrayList<String>();[/b]
    }
 
    public void setNumbers(Set<Integer> numbers) {
        // can accept any kind of Set
        this.numbers = numbers;
    }
}

Open in new window


can we have generic List as return type to provide more flexibility to future changes to collection implementation?
https://www.codejava.net/coding/10-java-core-best-practices-every-java-programmer-should-know
Please advise
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
IT Business Systems Analyst / Software Developer
Top Expert 2015
Commented:
Yes!
ste5anSenior Developer
Commented:
No.

Cause the reason for choosing the correct type is not "being future proof". This would be an wasted effort.

The reason for choosing a more generic type is that you're able to change between different kind of collections used in your implementation. This is part of polymorphism in OOP.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial