简体   繁体   中英

Looping through a List in Java

Please help me understand, the below code is showing Type mismatch: "cannot convert from element type Object to List" in the for statement. I know I'm missing something silly. Please help.

public void setMapPriceValue(SolrItemVO solrItemVO, ArrayList proce1) throws SolrDAOException
{
    List xcatentAttrList = (List<Xcatentattr>) proce1.get(0);

    solrItemVO.setMapPrice(-1); // setting default value

    for(List  xcatentattr : xcatentAttrList){

        if(xcatentattr.get(0) == 33)

                solrItemVO.setMapPrice(xcatentattr.get(1));

                solrItemVO.setMapPriceVal(xcatentattr.get(2));

        }

}

First you are mixing generics and raw types - it would make your life easier if you only used generics:

List<Xcatentattr> xcatentAttrList = (List<Xcatentattr>) proce1.get(0);

You might also consider using the correct generic type in your method signature (I assume proce1 is a list of list):

public void setMapPriceValue(SolrItemVO solrItemVO, List<List<Xcatentattr>> proce1)

In which case you don't need the cast any more:

List<Xcatentattr> xcatentAttrList = proce1.get(0);

Then the syntax for the enhanced for loop is for (TypeOfObjectInYourList object : list) , so in your case:

for(Xcatentattr xcatentattr : xcatentAttrList)

If you are going to type things try and keep them typed

List<Xcatentattr> xcatentAttrList = (List<Xcatentattr>) proce1.get(0);

solrItemVO.setMapPrice(-1); // setting default value

for(Xcatentattr  xcatentattr : xcatentAttrList){

    if(xcatentattr.get(0) == 33)

            solrItemVO.setMapPrice(xcatentattr.get(1));

            solrItemVO.setMapPriceVal(xcatentattr.get(2));

    }
}

then the answer might be clearer ;)

The for loop is of type Xatentattr. You are looping through the list of that type.

Take a look at this link for more info on for-each loops

There are two issues here.

  • First, if you declare List xcatentAttrList without using generics, Java can only know that your list contains Object s. So your for loop would have to iterate through a list of Object s.
  • Second, the cast (List<Xcatentattr>)proce1 implies the list contains Xcatentattr elements, and yet you are iterating through List objects.

So provided you had declared the List using generics (and therefore saying you are working with a list of Xcatentattr elements), the loop for would be:

 for (Xcatentattr xcatentattr : xcatentAttrList) {
     . . .
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM