0

I see no reason why Eclipse produces yellow squiggly lines(warning) underneath the line of code where Im creating a new ArrayList inside method m1(). When I cannot add a non-String object to the Collection c anyways, why does the IDE wants a <> right next to new ArrayList? At execution time, they are type erased also so trying to understand if it really means anything.

import java.util.ArrayList;
import java.util.Collection;

public class Main {

    public static void main(String[] args) {
        m1();
    }

    private static  Collection<String> m1() {
        Collection<String> c = new ArrayList();//gives typesafety warning for missing <>
        c.add("A");
        c.add("B");
        c.add(1); // does not let me add a non-String type anyways
        return c;
    }
}
greg-449
  • 109,219
  • 232
  • 102
  • 145
JavaNovice
  • 1,083
  • 1
  • 12
  • 20

1 Answers1

1

The warning is giving for new ArrayList();, as you are creating ArrayList object without generics. Even you have provided generic for reference variable, there are case in which you can add other than String class objects. Like:

You are creating like: Collection<String> c = new ArrayList();. As the reference is having generic type String compiler will check only reference and will not allow anything other than string. But in case:

Collection<Integer> intColl = (Collection)c;

In this case you can even add integer in collection. That's why it is giving the warning.

Deepak Kumar
  • 1,246
  • 14
  • 38