2013-03-27 32 views
3

我得到的錯誤:ClassCastException異常在Java錯誤對象[]爲String []

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; 
at Book.Organizer.Desk.RubCol.BookMainKeeper.main(BookMainKeeper.java:25) 

我不知道如何解決這個問題。任何人都可以通過告訴我我做錯了什麼來幫助我嗎?

主要(BookMainKeeper類):

public class BookMainKeeper { 

/** 
* @param args 
*/ 
public static void main(String[] args) { 

    BagInterface<String> shelf1 = new pileBooks<String>(); 
    BagInterface<String> shelf2 = new pileBooks<String>(); 
    BagInterface<String> shelf3 = new pileBooks<String>(); 

    shelf1.add("Java 3rd Edition"); 
    shelf1.add("Pre-Calculus 2nd Edition"); 
    shelf1.add("Lava World"); 

    String[] check = shelf2.toArray(); 

    System.out.println(shelf2.toArray()); 

}} 

pileBooks類使用BagInterface:在pileBooks類使用

public class pileBooks<T> implements BagInterface<T> { 

private final T[] bag; 
private static final int DEFAULT_CAPACITY = 25; 
private int numberOfEntries; 

/** Creates an empty bag whose initial capacity is 25. */ 
public pileBooks() 
{ 
    this(DEFAULT_CAPACITY); 
} // end default constructor 

/** Creates an empty bag having a given initial capacity. 
@param capacity the integer capacity desired */ 
public pileBooks(int capacity) 
{ 
    numberOfEntries = 0; 
    // the cast is safe because the new array contains null entries 
    @SuppressWarnings("unchecked") 
    T[] tempBag = (T[])new Object[capacity]; // unchecked cast 
    bag = tempBag; 
} // end constructor 

/**gets the current size of the bag 
* @return numberOfEntries 
*/ 
public int getCurrentSize() { 
    return numberOfEntries; 
} 

/** Sees whether this bag is full. 
    @return true if this bag is full, or false if not */ 
public boolean isFull() 
{ 
    return numberOfEntries == bag.length; 
} // end isFull 

/**It checks if the bag is empty or not 
* @return True if numberOfEntries equals 0, False if otherwise 
*/ 
public boolean isEmpty() { 
    return numberOfEntries == 0; 
} 

/** Adds a new entry to this bag. 
@param newEntry the object to be added as a new entry 
@return true if the addition is successful, or false if not */ 
public boolean add(T newEntry) 
{ 
    boolean result = true; 
    if(isFull()) 
    { 
     result = false; 
    } 
    else 
    { 
     bag[numberOfEntries]= newEntry; 
     numberOfEntries++; 
    } 
    return result; 
} // end add 

/** Removes one unspecified entry from this bag, if possible. 
    @return either the removed entry, if the removal 
      was successful, or null */ 
    public T remove() 
    { 
     T result = null; 
     if(numberOfEntries>0) 
     { 
      result = bag[numberOfEntries-1]; 
      bag[numberOfEntries - 1]=null; 
      numberOfEntries--; 
     } 
     return result; 
    } // end remove 

/** Removes one occurrence of a given entry from this bag. 
    @param anEntry the entry to be removed 
    @return true if the removal was successful, or false otherwise */ 
public boolean remove(T anEntry) 
{ 
    int index = getIndexOf(anEntry); 
    T result = removeEntry(index); 
    return anEntry.equals(result); 
} // end remove 

/** 
* Removes entry by verifying it's index 
* @param index = variable to check, if it is -1, the entry was not found 
* and it will exit, if it is 0 or higher, it means it was found in the bag 
* @return if index is -1, it returns result as null 
* if index is 0 or higher, it will put bag[index] in the variable result 
* and returns result 
*/ 
protected T removeEntry(int index) { 
    T result = null; 
    int check = numberOfEntries; 
    if(index != -1) 
    { 

     while((index < numberOfEntries) && ((check-1) != numberOfEntries)){ 



      if(index == (numberOfEntries-1)) 
      { 
       result = bag[numberOfEntries-1]; 
       bag[numberOfEntries-1] = null; 
       numberOfEntries--; 
       break; 
      } 
      else 
      { 
       result = bag[index]; 
       bag[index] = bag [numberOfEntries-1]; 
       bag[numberOfEntries-1] = null; 
       numberOfEntries--; 
       break; 
      } 
     } 
    } 
    return result; 
} 



/** 
* verfifies if anEntry is inside the bag, if it is found, it assigns 
* i to the variable index 
* @param anEntry = object to search for inside the bag 
* @return index, -1 if anEntry was not found 
* whatever is contained in variable 'i' if it is found 
*/ 
private int getIndexOf(T anEntry) { 
    int index=-1; 
    for(int i=0;i<bag.length;i++) 
    { 
     if(anEntry.equals(bag[i])) 
     { 
      index = i; 
      break; 
     } 
    } 
    return index; 
} 







/** Removes all entries from this bag. */ 
public void clear() 
{ 
    while(!isEmpty()) 
     remove(); 
} // end clear 




/** Counts the number of times a given entry appears in this bag. 
@param anEntry the entry to be counted 
@return the number of times anEntry appears in the bag */ 
public int getFrequencyOf(T anEntry) 
{ 
    int counter = 0; 
    for(int index = 0; index < numberOfEntries; index++) 
    { 
     if (anEntry.equals(bag[index])) 
     { 
      counter++; 
     } 
    } 
    return counter; 
} // end getFrequencyOf 






/** Tests whether this bag contains a given entry. 
@param anEntry the entry to locate 
@return true if this bag contains anEntry, or false otherwise */ 
public boolean contains(T anEntry) 
{ 
    boolean found = false; 
    for(int index = 0; !found && (index<numberOfEntries); index++) 
    { 
     if(anEntry.equals(bag[index])) 
     { 
      found = true; 
     } 
    } 
    return found; 
} // end contains 






/** Retrieves all entries that are in this bag. 
@return a newly allocated array of all the entries in the bag */ 
public T[] toArray() 
{ 
    //the cast is safe because the new array Contains null entries 
    @SuppressWarnings("unchecked") 
    T[] result = (T[])new Object[numberOfEntries];//unchecked cast 
    for(int index=0;index < numberOfEntries; index++) 
    { 
     result[index]=bag[index]; 
    } 
    return result; 

} // end toArray 
} 

BagInterface:

//An interface that describes the operations of a bag of objects. 
public interface BagInterface<T> { 

/** Gets the current number of entries in this bag. 
@return the integer number of entries currently in the bag */ 
public int getCurrentSize(); 

/** Sees whether this bag is full. 
@return true if the bag is full, or false if not */ 
public boolean isFull(); 

/** Sees whether this bag is empty. 
@return true if the bag is empty, or false if not */ 
public boolean isEmpty(); 

/** Adds a new entry to this bag. 
@param newEntry the object to be added as a new entry 
@ return true if the addition was successful, or false if not */ 
public boolean add(T newEntry); 

/** Removes one unspecified entry from this bag, if possible. 
@return either the removed entry, if the removal was successful, or null */ 
public T remove(); 

/** Removes one occurrence of a given entry from this bag, if possible. 
@param anEntry the entry to be removed 
@return true if the removal was successful, or false if not */ 
public boolean remove(T anEntry); 

/** Removes all entries from this bag. */ 
public void clear(); 

/** Counts the number of times a given entry appears in this bag. 
@param anEntry the entry to be counted 
@return the number of times anEntry appears in the bag */ 
public int getFrequencyOf(T anEntry); 

/** Test whether this bag contains a given entry. 
@param anEntry the entry to locate 
@return true if the bag contains anEntry, or false otherwise */ 
public boolean contains(T anEntry); 

/** Creates an array of all the entries that are in this bag. 
@return a newly allocated array of all entries in the bag */ 
public T[] toArray(); 


}// end BagInterface 
+1

您的'toArray()'方法正在製作一個Object []而不是'String []'。 – 2013-03-27 20:13:33

+0

你需要調用toArray(new String [0])。 toArray()返回Object [],如上所述 – kofemann 2013-03-27 20:25:42

回答

1

你可以不投Object[]String[]就像你不能投ObjectString。您可能需要返回類型T的實際陣列。

如何執行此操作?一種方法是增加數組類型的toArray參數一樣

public T[] toArray(Class<T> clazz) { 
    // the cast is safe because the new array Contains null entries 
    @SuppressWarnings("unchecked") 
    T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, numberOfEntries); 

或者,如果你確信數組將只包含T類型的對象,但不是它的亞型像某種T1T2你可以得到的類型陣列由存儲單元的一個閱讀它像

T[] result = (T[]) java.lang.reflect.Array.newInstance(
     bag[0].getClass(), numberOfEntries); 

,但我要說的是第一種方式比較好,因爲它讓你創建所需類型的數組,並消除風險,你將創造某種T1的陣列鍵入而不是T

+0

老實說,我不明白你放的代碼......我將如何定義getClass()的內容,或者toArray(Class clazz)如何工作?我是一個noob,我知道.. – AndyApps 2013-03-30 14:43:50

+0

@AndyApps每個對象都包含有關它的類的信息。爲了在真正的瓦片中獲得這些信息(當程序運行時),你可以使用'yourObject.getClass()'。這個方法將返回'Class'的實例,其中包含類的元信息,例如類的全名,關於其字段的信息(可見性,類型,名稱),方法等等。通過這個對象和'java.lang.reflect.Array',你可以創建和類一樣完全相同的數組 - 類型爲'new SameClassAsPreviousObject [size]'。 – Pshemo 2013-03-30 14:59:57

+0

所以在主要我會使用.toArray(pileBooks x)或類似的東西,並在toArray我會使用類似reflect.Array的東西? – AndyApps 2013-03-30 15:09:09

0

你應該把它保存到一個對象數組,而不是一個String數組:

Object[] check = shelf1.toArray(); 

System.out.println(check[1].toString()); 
System.out.println(check[2].toString()); 
System.out.println(check[3].toString()); 

打印:

Java 3rd Edition 
Pre-Calculus 2nd Edition 
Lava World 

check是對象的數組。 Object類是所有類的父類,包括String。它在運行時檢查,這就是爲什麼你的代碼編譯,但在執行過程中得到一個錯誤。