迭代ArrayList </user>的泛型类型<user>

时间:2012-06-04 14:24:00

标签: java collections

我正试图从arraylist中获取值。

我有User类型bean类,如下所示..

class User{

      public String link;
      public String url;

     User(String l,String u){
           this.link=link;
           this.url=url;
      }
setters and getters below.. 

我在这里尝试用main编写一个类。

public class ListClass{
      public static void main(String args[]){
            List<User> list = new ArrayList<User>();
            list.add(new User("link1","url1"));
            list.add(new User("link2","url2"));
            list.add(new User("link3","url3"));

            //here i want to iterate both links and urls one by one 

            Iterator it=list.iterator();
            // remaining the code to get both link1 and url1 ..
}

我需要输出为:

link1  url1
link2  url2
link3  url2

4 个答案:

答案 0 :(得分:10)

您可以使用for-in构造而不是Iterator:

for (User u : list) {
  System.out.println(u.link + " " + u.url);
}

如果你肯定想使用迭代器:

Iterator<User> it=list.iterator();
while (it.hasNext()) {
  User u = it.next();
  System.out.println(u.link + " " + u.url);
}

答案 1 :(得分:2)

正如其他用户已经说过的那样,您可以使用enhanced for statement。考虑为toString()添加User实施:

class User
{
    @Override public String toString()
    {
        return this.link + " " + this.url;
    }
}

会将循环减少到:

for (User u: list)
{
    System.out.println(u);
}

答案 2 :(得分:0)

for (User u : list) {
   System.out.println(u.getLink() + "  " + u.getUrl());
}

答案 3 :(得分:0)

如果你坚持使用itereator:

Iterator<User> it = list.iterator();
while(it.hasNext()) {
   /...
   it.next();
}