【问题标题】:Cannot cast to class . . . are unnamed module of loader无法转换为 class 。 . .是 loader 的未命名模块
【发布时间】:2020-11-13 22:01:29
【问题描述】:

我正在尝试使用链表实现从头开始创建优先级队列 ADT。在优先级队列中,我需要插入作业,并且作业必须按优先级顺序执行。我构造的优先级 ADT 来自我的 Java 书籍,而我的 Job 类是由我创建的。我可以将所有作业插入优先级队列,但是当我尝试 removeMin() 时,我得到一个无法转换的类...错误。

这是我获取数组、将它们放入队列并删除它们的方法。

public static void executeJobs(Job[] jobInputArray) {

    SortedPriorityQueue pq = new SortedPriorityQueue();
    
    for(int j = 0; j < jobInputArray.length; j++) {
        pq.insert(jobInputArray[j].getFinalPriority(), jobInputArray[j]);
        jobInputArray[j].setEntryTime(j+1);
    }
    
    int cycles = 0;
    
    while(!pq.isEmpty()) {
        Job currentJob = (Job) pq.removeMin();
        System.out.println(currentJob.getJobName());
    }
}

问题出现在我的:Job currentJob = (Job) pq.removeMin();行。

这是我的 SortedPriorityQueue 类:

public static class SortedPriorityQueue<K,V> extends AbstractPriorityQueue<K,V>{
private PositionalList<Entry<K,V>> list = new LinkedPositionalList<>();

public SortedPriorityQueue() { super(); }
public SortedPriorityQueue(Comparator<K> comp) {super(comp);}

public Entry<K,V> insert(K key, V value) throws IllegalArgumentException{
    checkKey(key);
    Entry<K,V> newest = new PQEntry<>(key,value);
    Position<Entry<K,V>> walk = list.last();
    
    while(walk != null && compare(newest, walk.getElement()) < 0)
        walk = list.before(walk);
    if(walk == null)
        list.addFirst(newest);
    else
        list.addAfter(walk, newest);
    return newest;
}
public Entry<K,V> min(){
    if (list.isEmpty()) return null;
    return list.first().getElement();
}

public Entry<K,V> removeMin(){
    if(list.isEmpty()) return null;
    return list.remove(list.first());
}
public int size() {return list.size();}

}

任何帮助都非常感谢..提前感谢!

【问题讨论】:

  • 请在您的问题中添加确切的错误消息。
  • 线程“主”java.lang.ClassCastException 中的异常:类 helloworld.helpers$AbstractPriorityQueue$PQEntry 无法转换为类 helloworld.Job(helloworld.helpers$AbstractPriorityQueue$PQEntry 和 helloworld.Job 在加载程序'app'的未命名模块)
  • removeMin 返回什么类型?在您的情况下,K 和 V 被实例化为什么?

标签: java


【解决方案1】:

removeMin 返回 Entry&lt;K,V&gt;,而不是 Job。它不能转换为Job。缺少 Entry 的实现,但我认为它有 value()getValue() 方法:

Job currentJob = (Job) pq.removeMin().getValue();

【讨论】:

  • 天哪,我太愚蠢了......我整天都在玩这个。我不知道为什么它没有点击我
  • @FalseOccasion 如果您使用new SortedPriorityQueue&lt;KeyType, Job&gt;() 实例化您的队列,那么您根本不需要强制转换。 getValue() 已经返回正确的类型。如果可以避免,请不要使用原始类型。
  • 明白了!快速提问,但是有没有办法遍历我使用增强的 for 循环搜索值的优先级队列?
  • @FalseOccasion:让你的班级实现Iterable interface
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多