Reputation:
For my class we have to write the Java code for the Radix Sort algorithm. I understand the algorithm, and I thought I had the solution, but I'm getting an incompatible types error in my code and I don't understand why.
import java.util.*;
public class RadixSort {
public static void radixSort(int[] list) {
// will be passed to getKey to decide what to divide the number by before %10
int div = 1;
// repeat once for the max number of digits of the numbers
for (int i = 0; i < 3; i++) {
ArrayList bucket[] = new ArrayList[19];
// distribute the elements from the list to the buckets
for (int j = 0; j < list.length-1; j++) {
int key = getKey(list[j], div);
// add 9 so that if key is negative, it will now be 0 or positive so an out of bounds exception isn't thrown
// so bucket[0] means the key was -9, and bucket[18] means the key was 9
if (bucket[key+9] == null)
bucket[key+9] = new ArrayList();
bucket[key+9].add(list[j]);
}
// move the elements from the buckets back to list
int z = 0;
for (int x = 0; x < 19; x++) {
if (bucket[x] != null) {
for (int y: bucket[x]) { // incompatible types???
list[z] = y;
z++;
}
}
}
// multiply div by 10 for the next run-through
div = div*10;
}
}
public static int getKey(int i, int j) {
return (i/j) % 10;
}
// test method
public static void main(String[] args) {
int[] list = {922, 243, 409, 885, 96, 21, -342, 119, 540, 12, -732, 8, -3, 2};
radixSort(list);
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
}
}
I marked the line where I'm getting incompatible types. I don't want just how to fix it, but why the types are incompatible. I genuinely have no idea and I want to understand why. Thanks for any help.
Upvotes: 0
Views: 463
Reputation: 31
You declared bucket as a List of Object items, and an Object item can't be cast to an int value. So it throw a compilation error there. To fix the error, you can use Generics as @Elliott mentioned, or rewrite the code there as follow:
for (Object y: bucket[x]) {
list[z] = (Integer) y;
z++;
}
Upvotes: 3
Reputation: 201477
In order to use Generics you will need to type your ArrayList
, that is
ArrayList<Integer>
Upvotes: 1