[英]ClassCastException casting error
I'm getting an error on my code and I really dont understand why it's happening: 我的代码出现错误,我真的不明白为什么会这样:
for(Pacote<Par<String, Double>> pacote : pacotes) /snippet of code where the error occurs/
trying to cast it to 试图将其投射到
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;
}
}
public class Pacote { 公开课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;
}
Code around the line it is happening: 代码正在发生:
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++ + ":");
And I'm getting "Exception in thread "main" java.lang.ClassCastException: pack.Par cannot be cast to pack.Pacote", not sure why. 而且我收到“线程“ main”中的异常” java.lang.ClassCastException:pack.Par无法转换为pack.Pacote”,不知道为什么。 Can someone help?
有人可以帮忙吗?
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;
}
Your declaration of Par
is incorrect. 您对
Par
声明不正确。 I suppose you want it to be an inner class, but you haven't declared it as class. 我想您希望它是一个内部类,但是您尚未将其声明为类。
public Par (A itemA, B itemB){
this.tipo=itemA;
this.peso=itemB;
}
This is a constructor, but it is treated as constructor to the surrounding class, with is Pacote
, not Par
, so you do not actually have a class Par
... 这是一个构造函数,但是它被视为周围类的构造函数,使用
Pacote
而不是Par
,因此您实际上没有Par
类 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.