• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using Comparable, Generics, and recursion to sort an array alphabetically  RSS feed

 
Jim Stevens
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So my assignment/goal is to great a static generic method to sort an arraylist of objects that implements comparable that sorts an array in ascending order. I have some code written up. My problem is when I get user input and run my code it does not sort my arraylist. I get no errors. It just spits out the array in the order they were entered. I feel like my problem is in the generic method. Any help or pointers would be great. Thanks

 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jim. Take a close look at your first if statement.
 
Jim Stevens
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya I found that right after i posted it. My next problem is

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 16, Size: 16
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Sort.sortArray(Sort.java:50)
at Sort.main(Sort.java:23)

my switch statements are causing some kind of index out of bounds....
 
Jim Stevens
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
solved...



needed to put the -1 on end
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two suggestions:
1) Declare variables and parameters as List, not ArrayList. That allows you to switch to LinkedList without many changes.

2) Change the generic type of your sortArray method to <T extends Comparable<? super T>>. Some classes do not implement Comparable themselves but instead their super class does. java.sql.Timestamp is such an example. It does not implement Comparable<Timestamp> but Comparable<Date> instead. By adding the ? super part you allow these classes to be used as well.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this question different than your other thread?
 
Jim Stevens
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeff Verdegan wrote:Is this question different than your other thread?


No this thread was a completely different question that I solved by adding break statements and walking through my program to diagnose my problems...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!