-2

I know i can create an instance of a Type Paramter using the method given here. But why doesnt the following statement compile?

public static <E> void append(List<E> list) {
    E elem = new E();  // compile-time error
    list.add(elem);
}

List<String>list=new ArrayList<String>();
append(list);

1.Cant the type of E be detected based on what i pass in the method append()? Then what is Type Inference used for?
2. Even if Type Inference is not applied, then wont E elem=new E() will b converted into Object elem=new Object() at run time, which should be fine? In any case, it should work. But why it doesnt?

EDIT: The duplicate qeustion that they have given link to only answers the methods by which we can create an instance of Type Parameter. It doesnt answer why this method wont work.

Diffy
  • 2,339
  • 3
  • 25
  • 47
  • 4
    Why do you think `new Object()` is fine? That is never what you want. – SLaks May 27 '15 at 18:23
  • Java needs to know at compile time how much memory a certain Object will take up. Furthermore, how is Java supposed to know about how many parameters the generic type will need upon instantiation, or whether the class is abstract, and therefore incomplete? These things need to be resolvable at compile time, before the application can be made executable. – Mapsy May 27 '15 at 18:26
  • @SLaks, i dont want it but it should be fine by the compiler. – Diffy May 27 '15 at 18:37
  • @Diffy: The compiler is trying to _discourage_ you from writing code that doesn't do what you want. – SLaks May 27 '15 at 18:37
  • Who closed the question? Does the question they have given link to even answers what i am asking here? – Diffy May 27 '15 at 18:37
  • @AlexT.: Actually, the compiler does not need to know anything about memory. – SLaks May 27 '15 at 18:38
  • I just gave it some thought and that's so obvious, otherwise there'd be no way you could make a dynamic array! Ignore me. ;p – Mapsy May 27 '15 at 18:39

1 Answers1

4
  1. No. Type inference is a syntactic feature; it means that the compiler infers at the callsite so that you don't need to explicitly write <String> append(list).

  2. No. That would violate compile-time type safety. E might not be Object, so an Object cannot be implicitly converted to an E.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964