• Post Reply Bookmark Topic Watch Topic
  • New Topic

Headfirst Java sorting page 566  RSS feed

 
Elim Banda
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please help look at the pictures the highlighted part. I know the first part is the reference but whats the other bit is confusing "(boo) b". can somebody please tell me whats going on there so confusing the more detail the better
page-566-headfirst.PNG
[Thumbnail for page-566-headfirst.PNG]
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is old‑fashioned code because it doesn't use generics. What you have to do it assume that the Object parameter passed is in fact a Book, and then cast it to a Book object, not boo. What you are telling the javac tool is, “Don't worry; I know it will be a Book.”
You would write something different nowadays:-Now, there is no risk of passing the wrong type; the compiler will notice and not permit the wrong type.
Note that the title given here is a String and String already implements Comparable<String>, so you can implement that method quite simply by borrowing the String version.
 
Piet Souris
Master Rancher
Posts: 2042
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Elim,

as you can see, the parameter is 'Object b' in the compareTo method. Now, an Object does not have a field called 'title'. So, assuming that b is actually a Book, we must cast b to a Book with:

and now we can use book.title.

Mind you, this is old non--generic code. If b is not a (subclass of a) Book, then this code will raise a ClassCastException.

I cannot see what the book is telling about the generic version of Comparable, but nowadays you would use:

and the compareTo method would have a Book b as argument, so there is no need to do a cast anymore.
 
Mohammed Sardar.
Ranch Hand
Posts: 193
1
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course, please don't forget to upgrade your JDK version to greater than 1.5 as generics came into picture from Java 5.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!