• Post Reply Bookmark Topic Watch Topic
  • New Topic

Autoboxing and Unboxing in Generics  RSS feed

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two related questions ask:

Given the followng method header, can the lists in 21.10 and 21.11 be passed into the method.




21.10 Given int[] list = {1, 2, -1}, can you invoke sort(list) using the sort
method in Listing 21.4?

21.11 Given int[] list = {new Integer(1), new Integer(2), new Integer(-1)},
can you invoke sort(list) using the sort method in Listing 21.4?


________________

I would claim, "yes", in both cases. In the first case, ints are automatically wrapped into Integer objects; in the second case, the data structures are already objects.
This disagrees with the answer key, however, which claims:

No, because list is of type int[], but the sort method requires E[], where E is an object type.

No, because list is still of type int[], but the sort method requires E[], where E is an object type.


Is my understanding wrong?
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What lists? You are passing arrays.

Please tell us where the question is from to avoid copyright problems.

Both questions have the same answer, because in example 2 the Integers are unboxed, so you are dealing with an array of ints for both. Go through the Java™ Tutorials about generics (second section here), and you find that generics has to be applied to an object. And int[] is an object, but its elements are not objects, so it can never be described as an E[]. You will have to go through the Java® Language Specification, and also write a program which tries the code. Also try a castI am pretty sure that will fail too!
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will also find that boxing is not applied to array elements like that.
 
Aahan Agrawal
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question was taken from Daniel Liang's Introduction to Java textbook.

I understand your point. Thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!