java 迭代 ArrayList 的通用类型<用户>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10882943/
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
Iterate Generic type<User> of ArrayList
提问by Mdhar9e
I am trying to get the values from an arraylist.
我正在尝试从数组列表中获取值。
I have the User type bean class as below..
我有 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..
Here I am trying to write a class with main.
在这里,我试图用 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 ..
}
I need the output as:
我需要输出为:
link1 url1
link2 url2
link3 url2
回答by Alexander Pavlov
You can use the for-in construct instead of the Iterator:
您可以使用 for-in 构造而不是 Iterator:
for (User u : list) {
System.out.println(u.link + " " + u.url);
}
If you definitely want to use the iterator:
如果您确实想使用迭代器:
Iterator<User> it=list.iterator();
while (it.hasNext()) {
User u = it.next();
System.out.println(u.link + " " + u.url);
}
回答by hmjd
As has already been stated by other users you can use the enhanced for
statement. Consider also adding a toString()
implementation for User
:
正如其他用户已经声明的那样,您可以使用增强for
声明。还考虑添加一个toString()
实现User
:
class User
{
@Override public String toString()
{
return this.link + " " + this.url;
}
}
which would reduce the loop to:
这会将循环减少到:
for (User u: list)
{
System.out.println(u);
}
回答by Jeremy Goodell
for (User u : list) {
System.out.println(u.getLink() + " " + u.getUrl());
}
回答by Edwin Dalorzo
And if you insist with itereator:
如果你坚持使用迭代器:
Iterator<User> it = list.iterator();
while(it.hasNext()) {
/...
it.next();
}