| Author |
What is wrong with my generic implementation of sort method ?
|
Praveen Kumar Singh
Ranch Hand
Joined: Mar 04, 2009
Posts: 43
|
|
Hi
For Input: [abc, abb, aaa, bbc]
Collections.sort give: [aaa, abb, abc, bbc]
I tried to implement something similar to it like this
But what i get is: [abb, aaa, abc, bbc]
Why ?.....Any Help !!
|
Praveen
SCJP, SCWCD, SOA
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16487
|
|
It's probably just a bad implementation of bubble-sort. Nothing to do with generics, I wouldn't think.
(It would be better if the method's name was "doBubbleSort" rather than "doBubbleShort" but that isn't the source of your problem.)
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3865
|
|
Think about the scope of your inner loop.
Because you're looping from the start to finish, at the end of one iteration you've got the last element in the right place. So the next iteration you need to move across all elements except the last one. But instead, you're moving across all but the first.
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
If you change your method definition to:
Then you don't need to cast. Also oneSwap is never used.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
Wouter Oet wrote:If you change your method definition to:
Then you don't need to cast. Also oneSwap is never used.
Make that Without the ? super part you couldn't sort a List<java.sql.Timestamp>, as Timestamp extends java.util.Date and therefore implements Comparable<Date> - not Comparable<Timestamp>.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Praveen Kumar Singh
Ranch Hand
Joined: Mar 04, 2009
Posts: 43
|
|
Thanks Paul and Matthew
Its end up in wrong implementation only !
I almost presume that error is in 'generic' logic only
Final code
Thanks Wouter
Its works very well
I definitely need more study on Generics !
Thanks Rob
Look like you are an expert on generics
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
Expert, no. I am somewhat experienced though, even though I didn't switch from Java 1.4 to Java 5.0 for the first year or so.
|
 |
 |
|
|
subject: What is wrong with my generic implementation of sort method ?
|
|
|