
Iterator hmKey=cartBooks.keySet().iterator();
while (hmKey.hasNext()){
long hmId= (Long )hmKey.next();
if(hmId==pid){
return true;
}
}
return false;
}
long hmId= (Long )hmKey.next();出错说不能强制转换就解答
你的哗凯Map里面存放的对象类型明显不搏亏是Long,你直接用System.out.println("" + hmKey.next().getClass());
把基芦神对象类型输出来看看.
xujianhang0204说的编译时不报错,而运行时报错的情况就是明显的类型不匹配.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Test t = new Test();
Map
cartBooks.put(new Long(11), "xxx");
cartBooks.put(new Long(12), "旁禅yyy");
cartBooks.put(new Long(13), "zzz"链启谨);
System.out.println(t.existCartBook(cartBooks, 12));
}
public boolean existCartBook(Map cartBooks, long pid) {
Iterator hmKey = cartBooks.keySet().iterator();
while (hmKey.hasNext()) {
long hmId = (Long) hmKey.next();
if (hmId == pid) {
return true;
}
}
return false;
}
}
cartBooks里知拍扰面不全是long类型搭旦的数贺大据造成的。
一楼的,Iterator是迭代器。
建议对Map使用泛型。
我在clipise上试了试,不运行是不会报错的;
我认为你的程序段在语法上是没有错误的。
你的Key是Long类型嘛???不是转肯定出错呀。
类型不一致当然不能强制转换