Java 类型不匹配:无法从对象转换为列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22194413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type mismatch: cannot convert from Object to List
提问by Kiran
CompanyDAO companyDAO = new CompanyDAO();
List companyList = companyDAO.getAllCompanyList();
MycompanyList contains a data of like this :
MycompanyList 包含这样的数据:
[[1, Agastha Medical Center], [2, Agastha Asthma]]
Now i want to iterate the values and i want to pass a value of 1 to query but when i am placing this inside of a for loop i am getting
现在我想迭代这些值,我想将值 1 传递给查询,但是当我将它放在 for 循环中时,我得到了
for(int k=0;k<=companyList.size();k++){
List companyId =companyList.get(k); // [1, Agastha Medical Center] for k=0;
Type mismatch: cannot convert from Object to List
I need to read value of 1 alone inside of for loop how can i do this ?
我需要在 for 循环中单独读取 1 的值我该怎么做?
回答by Smutje
As your companyList is of raw type, you have to cast the object obtained from it explicitly
由于您的 companyList 是原始类型,您必须显式转换从中获得的对象
List companyId = (List) companyList.get(k);
But it would be better to provide your API with types so that casting is not necessary.
但是最好为您的 API 提供类型,这样就不需要强制转换了。
回答by TheLostMind
- Don't use raw types use generics. example :
Arraylist<String>- List companyId =companyList.get(k) is your error. companyList.get(k) returns an object. you have to typecast it to appropriate type explicitly.
- 不要使用原始类型使用泛型。例子 :
Arraylist<String>- List companyId =companyList.get(k) 是你的错误。companyList.get(k) 返回一个对象。您必须明确地将其类型转换为适当的类型。
回答by xiriusly
Provide the Type of list you want to get from CompanyDAO
提供您想从 CompanyDAO 获取的列表类型
Ex. ArrayList<Company>, List<Company>
前任。ArrayList<Company>,List<Company>
回答by Engineer
you have to type cast the list
你必须输入列表
for(int k=0;k<=companyList.size();k++){
List companyId =(List)companyList.get(k);

