开发者

Cannot iterate through array

UserType statuses = twitter.getFriendsStatuses(UserType.class, null, null);
for( UserType  users :  statuses )
{
     out.println("<p>"+users.getName()+"</p>");
}

I get an error "Foreach not applicable to expression type".


my methods definition is this:

public <T> T getFriendsStatuses(Class<T&g开发者_运维技巧t; responseType, String lite, String page) throws UniformInterfaceException {
        String[] queryParamNames = new String[]{"lite", "page"};
        String[] queryParamValues = new String[]{lite, page};
        return webResource.queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
    }


That is because UserType does not implement Iterable<T>. Thus, you can not use the enhanced for (foreach) loop to iterate over it.


EDIT: Given the example you provided, my wild guess is that the code was generated by Jersey. If that is the case, then you should be using Statuses.class instead of UserType.class. Then, you can get a List of StatusType, which you can then use in the for loop, since List implements Iterable.

Statuses statuses = twitter.getFriendsStatuses(Statuses.class, null, null); 
for (StatusType statusType : statuses.getStatus()) {
  UserType userType = statusType.getUser();
  System.out.println("<p>" + userType.getName() + "</p>");
}

But then again, it is just a wild guess.


Does UserType implement Collection or Iterable?

You can only apply for each to collections or arrays (or anything implementing Iterable).

http://leepoint.net/notes-java/flow/loops/foreach.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜