Reputation: 87
I'm trying to sort an array of records. But I get "not a Record" error. The method getCt() is in a different class, the program compiles and the array is of the record type. I really don't know what is wrong with this code.
HashTable:
public class HashTable {
private Record [] array;
private int size;
private int indexSize=0;
private boolean updated,found;
public HashTable(int m){
array= new Record[m];
size=0;
}
public void getCt() {
Arrays.sort(array);
// return array[0];
}
Record class:
import java.lang.Comparable;
import java.util.*;
public class Record implements Comparable {
private Integer count;
private DNSkey key;
public Record(DNSkey key) {
this.key = key;
count = 1;
}
public void update() {
count++;
}
public DNSkey getKey() {
return key;
}
public Integer getCount() {
return count;
}
public int compareTo(Object obj) {
if (!(obj instanceof Record)) {
throw new ClassCastException("Not a Record");
}
Record check = (Record) obj;
return getCount().compareTo(check.getCount());
}
public String toString() {
return getKey() + " " + getCount();
}
}
Upvotes: 0
Views: 486
Reputation: 516
My guess would be null items in the array. "null instanceof Class" will return false.
This will throw the Exception:
Record[] array = new Record[] { new Record(...), null };
Arrays.sort(array);
Upvotes: 3
Reputation: 332
one easy way is to use generics :
public class Record implements Comparable<Record> {
...
public int compareTo(Record check){
return getCount().compareTo(check.getCount());
}
Upvotes: 3