簡體   English   中英

ClassCastException強制轉換錯誤

[英]ClassCastException casting error

我的代碼出現錯誤,我真的不明白為什么會這樣:

for(Pacote<Par<String, Double>> pacote : pacotes) /snippet of code where the error occurs/

試圖將其投射到

 public class Pacote <E> {

    private int capacidade;
    private ArrayList <E> pacote;

    public Pacote (int capacidade){

        pacote= new ArrayList <> (capacidade);
        this.capacidade=capacidade;
    }


  public Par (A itemA, B itemB){
      this.tipo=itemA;
      this.peso=itemB;
  }

  public A primeiro(){

      return tipo;
  }

  public B segundo () {

      return peso;
  }

}

公開課Pacote {

private int capacidade;
private ArrayList <E> pacote;

public Pacote (int capacidade){

    pacote= new ArrayList <> (capacidade);
    this.capacidade=capacidade;
}

public int getCapacidade (){

    return capacidade;
}

public int getNumItems (){

    return pacote.size();
}

public boolean estaCheio () {

    return getNumItems()<capacidade-1;
}

public boolean empacota (E item){
    if (estaCheio())
        return false;
    else { 
        pacote.add(item);
        return true;
    }
       }

public List<E> items(){

   List <E> list = pacote;

   return list;
}

代碼正在發生:

public static void main(String[] args) throws IOException {
        // Recebe os dados de input
        Scanner sc = new Scanner(System.in);
        System.out.println("Introduza o ficheiro com a lista de items a empacotar:");
        String fich = sc.nextLine();
        BufferedReader reader = new BufferedReader(new FileReader(fich));
        System.out.println("Introduza a capacidade dos pacotes:");
        int capacidade = Integer.parseInt(sc.nextLine());

        // Cria os pacotes
        List<Pacote<Par<String, Double>>> pacotes = 
                GestorPacotes.criaPacotes(reader, capacidade);
        reader.close();

        // Mostra a informacao dos pacotes
        System.out.println("Pacotes formados:");
        int index = 0;
        for(Pacote<Par<String, Double>> pacote : pacotes) {  /error here/
            System.out.println("Pacote " + index++ + ":");

而且我收到“線程“ main”中的異常” java.lang.ClassCastException:pack.Par無法轉換為pack.Pacote”,不知道為什么。 有人可以幫忙嗎?

 public static List<Pacote<Par<String, Double>>> criaPacotes(
BufferedReader fileReader, int capacidadePacotes)
throws IOException {
        List retorno = new ArrayList <> (6);
        String s;
        while ((s=fileReader.readLine())!=null){
            retorno.add(parseItem(s));
        }
        return retorno;

    }

您對Par聲明不正確。 我想您希望它是一個內部類,但是您尚未將其聲明為類。

public Par (A itemA, B itemB){
  this.tipo=itemA;
  this.peso=itemB;
}

這是一個構造函數,但是它被視為周圍類的構造函數,使用Pacote而不是Par ,因此您實際上沒有Par

暫無
暫無

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

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