我正在学习Android
,Java
我已经创建了一个类,让我们这样说
class x(){
public int a;
public string b;
}
Run Code Online (Sandbox Code Playgroud)
然后我启动这个类的列表,然后像这样添加值到它的属性
public ArrayList<x> GetList(){
List<x> myList = new ArrayList<x>();
x myObject = new x();
myObject.a = 1;
myObject.b = "val1";
mylist.add(x);
y myObject = new y();
myObject.a = 2;
myObject.b = "val2";
mylist.add(y);
return myList;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何循环访问GetList()返回的内容
我试过了
ArrayList<x> list = GetList();
Iterator<x> iterator = list.iterator();
Run Code Online (Sandbox Code Playgroud)
但我不知道这是不是这样做的正确方法,加上我不知道接下来要做什么我在迭代器上添加了一个断点,但它似乎是空的,列表有值思考
Cal*_*man 11
有两种方法可以做到这一点:
for
循环iterator
方法.for
环:for(x currentX : GetList()) {
// Do something with the value
}
Run Code Online (Sandbox Code Playgroud)
这就是所谓的"for-each"循环,它可能是最常见/首选的方法.语法是:
for(ObjectType variableName : InCollection)
您还可以使用标准for
循环:
ArrayList<x> list = GetList();
for(int i=0; i<list.size(); i++) {
x currentX = list.get(i);
// Do something with the value
}
Run Code Online (Sandbox Code Playgroud)
这个语法是:
for(someStartingValue; doSomethingWithStartingValue; conditionToStopLooping)
iterator
方法:Iterator<x> iterator = GetList().iterator();
while(iterator.hasNext()) {
x currentX = iterator.next();
// Do something with the value
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17179 次 |
最近记录: |