1

This question is specifically about nested lists which is a static field of the generic class. If I am maintaining the logs in a static variable inside my class using the code:

static List<List<? extends Number>> myLog = new ArrayList<List<? extends Number>>();

myLog is a list of list whose element is of type that extends Number. Here, instead of extending Number, I might want to use a generic type <? extends T>.

I understand that type variables exist only at compile time, and all instances of a generic class has the same run-time class, due to type erasure. Then, how is the nested list (List interface) within the top-level list (ArrayList) is determined at compile time about its actual implementation type (ArrayList,LinkedList, ...)? I find it a bit complex, as a couple of things are happening at the same time. Any help is appreciated.

EDIT: So, for example, in my code I have a method sortList which sorts a list of numbers, and it will also log that list of numbers in myLog list, like:

public void sortList(List<? extends Number> inList) {
    // do something
    myLog.addLast(inList);
    // do some more
}

Now, instead of using <? extends Number>, I might want to use <? extends T> in a generic class. So when creating the static field myLog, when type erasure happens, how does compiler determine the type of the nested list. I hope I am a bit clearer this time.

Lii
  • 11,553
  • 8
  • 64
  • 88
shujin
  • 181
  • 12
  • It sounds like you're not really sure what you're asking. Try to think it through and ask a specific question and we'll be in a much better position to help. – shmosel Oct 14 '16 at 05:57
  • I've edited the question. Hope I am a bit more understandable! – shujin Oct 14 '16 at 06:08
  • Type erasure happens after the type has been determined. – shmosel Oct 14 '16 at 06:10
  • "Then, how is the nested list ('List' interface) within the top-level list (ArrayList) is determined at compile time about its actual implementation type ?" You mean the `List extends Number>` in `ArrayList>();` ? – Asoub Oct 14 '16 at 07:55
  • @Asoub Yes, please. – shujin Oct 14 '16 at 20:07

1 Answers1

0

(as said in comments)

Type erasure hapens after the type has been determined and check.

In your code you described the type of myLog and the type of inList, so the compiler can determine at compile time if the types matches (and they do in both case) and thus, enforce the types.

Then type erasure happens, and types are lost for runtime (if you get myLog as a List you can add whatever you want, juste like if you described it as static List myLog).Well they're not completely lost: meta datas/refelction can give you these inforamtions, but they're not enforced anymore, like the compiler did.

Asoub
  • 2,273
  • 1
  • 20
  • 33