简体   繁体   中英

sorting using comparable java

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

one easy way is to use generics :

public class Record implements Comparable<Record> {

...

public int compareTo(Record check){
    return getCount().compareTo(check.getCount());
}

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

Use generics! And an @Override annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM