繁体   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