• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overloading efficiency.  RSS feed

 
Bob Ivanovich
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a case in which I want to sort two types of ArrayLists (using quicksort) and the method originally coded only accepts a String ArrayList. The problem is that now I want to sort an ArrayList of type int but couldn't . . . so I decided to overload the method. Since it looks very ugly to copy and paste the same chunk of code only to change the method signature I wondered if there is a better way to make this method more dynamic and be able to take in different types of ArrayLists.

My code:

 
Danijel Mitar
Greenhorn
Posts: 8
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes there is better and much nicer way. Try with generics and wildcard.

Oracle tutorial on generics
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have a look the definition of the sort() method in the Collections class - java.util.Collections#sort(java.util.List) - it might give you an idea of one way to do it (though don't worry too much about the <? super T> part if that's confusing - you can replace it with <T> for most purposes).

Though I assume this is some exercise in writing sort routines? Because if all you want to do is sort a List, just use the built in method and don't bother writing anything yourself.
 
Bob Ivanovich
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes this is just part of my class practice. I appreciate the suggestions and will make sure to look more into generics.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are copying and pasting code, assume that is wrong practice until proven otherwise.
 
Bob Ivanovich
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that . . . I decided to approach my goal a little bit differently considering that "copy paste" looks ugly.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!