-3

I know two reason to use generic List over List of objects.

  1. To restrict what type of objects can be inserted into the List

    List<Object> stringObjects = Arrays.asList("a",new Integer(5));
    List<String> genericStrings = Arrays.asList("a",new Integer(5));//compile error
    
  2. To have access to the correct method in your IDE

    List<Object> stringObjects = Arrays.asList("a",new Integer(5));
    List<String> genericStrings = Arrays.asList("a");
    stringObjects.get(0).length();//compile error
    genericStrings.get(0).length();
    

When I gave this answer to an interview, but they didn't seem very happy with my answer. So are there any other reason to user Generic List over List of objects?

Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59
Borislav Stoilov
  • 3,247
  • 2
  • 21
  • 46
  • 3
    Your title and final sentence aren't consistent. Which are you asking about? – Andy Turner Feb 03 '17 at 15:17
  • You are right. I have edited the question – Borislav Stoilov Feb 03 '17 at 15:19
  • 1
    Biggest two I can think of are non-reifiable generics and covariance of arrays. Then there are things like being able to create immutable lists, synchronize access etc. It's covered pretty comprehensively in *Effective Java 2nd Ed* Item 25 "Prefer lists to arrays". – Andy Turner Feb 03 '17 at 15:20
  • As an interviewer, I would followed up on your answer by asking why your first example is any different from `Object[] stringObjects = {"a", 5}; String[] genericStrings = {"a", 5};` in terms of compile-time safety, and similarly for your second example. – Andy Turner Feb 03 '17 at 15:24

2 Answers2

1

There are 2 main reasons:

  1. Stronger type checks at compile time.

  2. Elimination of casts.

source

rustyx
  • 80,671
  • 25
  • 200
  • 267
1

In my opinion, what you had in mind was correct, but no well formated.

It's not about "having access to the correct method in your IDE", it is about polymorphism and avoiding explicit cast.

public interface DoAble {
    void doSomething();
}

public Class FirstImpl implements DoAble {
    public void doSomething() {
        // Do something here
    }
}

public Class SecondImpl implements DoAble {
    public void doSomething() {
        // Do something here
    }
}

Usage with a List of Object

List list = new Arrays.asList(new SecondImpl(), new FirstImple());
for (Object o : list) {
    ((DoAble) o).doSomething();
}

It works, but it's ugly.

  • Since whatever can be inserted in the list, it can throw a java.lang.ClassCastException at any time.
  • We need to do an explicit cast, which we should always try to avoid.

Usage with Generic List

List<DoAble> list = new Arrays.asList(new SecondImpl(), new FirstImple());
for (DoAble o : list) {
    o.doSomething();
}

Easier to use and to read.

  • No explicit casts.
  • We are 100% that our list only contains objects that implements DoAble.
Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59