[英]Print out different item from Arraylist one after another
I will try to explain my problem. 我会尝试解释我的问题。 I have an Arraylist with several strings.
我有一个带有几个字符串的Arraylist。 I have an output method:
我有一个输出方法:
ArrayList<String> testList = new ArrayList<String>();
testList.add("test1");
testList.add("test2");
testList.add("test3");
testList.add("test4");
public static void output(int testIndex) {
for (int i = 0; i < testList.size(); i++) {
}
System.out.println("Domain: "+ testList.get(testIndex));
}
So depending on what data I need, I can use my output method and enter my values. 因此,根据我需要的数据,我可以使用输出方法并输入我的值。 If I enter 0 as testIndex, it will print out "test1".
如果我输入0作为testIndex,它将打印出“test1”。
I want to make this a little better though. 我想让这个好一点。 What I want to do is whenever I call my output method, I want it to print out the first item.
我想要做的是每当我调用我的输出方法时,我希望它打印出第一个项目。 When I call it again the second time, I want it to print out the second item.
当我第二次再次调用它时,我希望它打印出第二个项目。 When I call it a third time, I want to print out the third item.. and so on.
当我第三次打电话时,我想要打印出第三个项目..依此类推。
How do I do this? 我该怎么做呢? Can Java do this?
Java可以这样做吗? I also don't want to remove anything from my Arraylist.
我也不想从我的Arraylist中删除任何内容。
You could save the current position in a data member: 您可以将当前位置保存在数据成员中:
private static testIndex = 0;
public static void output() {
System.out.println("Domain: "+ chunkList.get(testIndex));
++testIndex;
}
What you need is to have a int value that is the counter that will increment each time you call the output method such as: 你需要的是有一个int值,它是每次调用输出方法时递增的计数器,例如:
int counter = 0;
and if you call your output method you then post increment it: 如果你调用输出方法,然后发布增量:
output(counter++);
Make sure you check if the counter is equal or greater than the size of your arraylist. 确保检查计数器是否等于或大于您的arraylist的大小。
Use queue instead of arraylist. 使用队列而不是arraylist。
Syntax is : 语法是:
Queue queue = new LinkedList();
queue.element()
To get the output without deleting it from the list 获取输出而不从列表中删除它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.