【发布时间】:2014-03-20 22:43:11
【问题描述】:
我的代码出现错误,我真的不明白为什么会这样:
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++ + ":");
我得到“线程“主”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;
}
【问题讨论】:
-
我很确定异常消息会告诉您涉及哪些类。您正在(通过使用泛型)进行非法强制转换。
-
请发布异常的完整堆栈跟踪,以便我们了解发生了什么。
-
你能在它发生的行周围显示代码吗?
pacotes是什么类型? -
使用stackoverflow.com/questions/3880997/… 作为参考,看起来您以某种方式在
pacotes中添加了Par。GestorPacotes.criaPacotes()是做什么的? -
@blueygh2 谢谢。但如何?什么是签名?我们能看到它的代码吗?看起来它应该返回
List时可能会返回List<Pacotes<Par<..>>>
标签: java