簡體   English   中英

創建和轉換對象數組時出錯

[英]Error creating and casting an array of objects

我試圖創建一個迭代器,在其中創建對象數組。 我必須鍵入強制類型轉換,因為不允許泛型數組創建。

我遇到運行時錯誤

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LRandomizedQueueList$Node;

迭代器的完整代碼如下所示。 我不知道我在做什么錯。

   private class RandomizedQueueIterator implements Iterator<Item> {
       private Node current = first;
       private Node[] ca = (Node[])new Object[size()];
       //private Node[] ca = new Node[size()];

       private RandomizedQueueIterator() {
           if (first == null) throw new NoSuchElementException();
           for (int j = 0; j < size(); j++) {
               ca[j] = current;
               current = current.next;
           }                        
           StdRandom.shuffle(ca);
           current = ca[0];
       }

       public boolean hasNext()  { return current != null; }

       public Item next() {
           if (current == null) throw new NoSuchElementException();
           Item item = current.item;
           current = current.next; 
           return item;
       }
       public void remove() {
           throw new UnsupportedOperationException("This method is not supported");
       }
   } 

感謝您在理解此錯誤方面的幫助。

采用:

private Node[] ca = new Node[size()];

創建數組時,無需強制轉換。 您可以只創建一個Node數組。

很明顯的例外:您不能將Object[] Node[]Node[] Object[]不是Node[]的子類。

替換為

private Node[] ca = new Node[size()];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM