0

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();
    }
}
6
  • 2
    So, how do you initialize your array? Commented Oct 3, 2012 at 10:17
  • 1
    Where is the array declared and initialised? Commented Oct 3, 2012 at 10:18
  • Just as a side note, homework tag is obsolete Commented Oct 3, 2012 at 10:19
  • 1
    array initialization is not shown Commented Oct 3, 2012 at 10:25
  • Ok, and where do you add elements to the array? Commented Oct 3, 2012 at 10:28

3 Answers 3

3

one easy way is to use generics :

public class Record implements Comparable<Record> {

...

public int compareTo(Record check){
    return getCount().compareTo(check.getCount());
}
Sign up to request clarification or add additional context in comments.

4 Comments

public class Record implements Comparable<Record> doesnt work
it should work, what is the version of java SDK you are using?
it does if your Java is 1.5 or later.
yes, you have to implement @Override public int compareTo(final @Nullable Record check) then (instead of the Object parameter type.
3

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);

1 Comment

in this case, adding if(obj==null) return 1; should fix it
-2

Use generics! And an @Override annotation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.