• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic class' constructor  RSS feed

 
Castor Tack
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, people:

Please look at the following code:



My question is:
TreeNode is a generic class, and TreeNode<E> is a type. TreeNode itself does not constitute a type, it's just a part of complete type. How can we do

The compiler is not supposed to know how much memory the key is going to take (key is of type E) until run time. So new will fail, won't it?

In my opinion, we should do



Could anyone please tell me the differences? and which one is better? and why the first version of code is correct?

Thank you.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My thoughts are that since you don't actually pass the object, but the REFERENCE to the object, it doesn't matter. The key might be 2 bytes or 10,000 bytes, but the reference to it will always be the same size, since it's (basically) just a pointer to the memory.

I'm not sure about this, though.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generics have not always existed in Java - they were added in Java 5. For backward compatibility, it is still possible to use raw types - you can use a generic type without the generic parameters.

This looks very strange and is not legal Java syntax:

What are trying to do here; create an array of Objects, and assign that to a TreeNode<E>[]?

You can find everything you ever wanted to know about generics in Java in Angelika Langer's Java Generics FAQ (warning, contains some complicated stuff, it might make your head spin!).
 
Castor Tack
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys.

I've got it.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!