1

This is a code just to know what is wrong and what is right.

public class JavaApplication5 {


public static void main(String[] args) {

  List l=new ArrayList<String>();//Line 1

  List<Object> x=new ArrayList<String>();//Line 2


}

 }

In the above line 1 is working fine but line 2 gives me compilation error. Can you tell me why?

Are not List and List<Object> equivalent? Either both should be wrong or both should be correct.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Shubham Tyagi
  • 181
  • 1
  • 3
  • 14
  • You are using different types in List on left side you have Object and on the right side you are instancing it as a Strings. – wedo Apr 09 '17 at 07:35
  • Possible duplicate of [Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – QBrute Apr 09 '17 at 07:38
  • what is difference between List and List – Shubham Tyagi Apr 09 '17 at 07:43
  • Raw types bypass generic type checks, deferring the catch of unsafe code to runtime. So `List` becomes `List` at runtime, whereas `List` is already known at compile time. Check out Oracle's tutorial on [type erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html) for more information. – beatngu13 Apr 09 '17 at 08:13

2 Answers2

1

You have to set the same Type in the both place :

List<Object> x = new ArrayList<String>();
//----^-------------------------^--------

So you have to option to solve your problem :

One don't set any type in your ArrayList

List<Object> x = new ArrayList<>();

Or set the same type :

List<Object> x = new ArrayList<Object>();
//or
List<String> x = new ArrayList<String>();
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

Neither posted option. For a List of String(s), since Java 7, you can use the diamond operator - like,

List<String> x = new ArrayList<>();

However, the older

List<String> x = new ArrayList<String>();

is still legal.

Your first option is a raw type, and your second option (if it were legal) makes a List that can contain any type of Object (not just String).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249