[英]How can i collect all items of an array
I have an array which is : 我有一个数组是:
ArrayList<Integer> array = new ArrayList<Integer>();
String a1 = edittext.getText().toString();
int integer = Integer.parseInt(a1);
array.add(integer);
like that. 像那样。 There are about 15 items but I don't know exactly how much they are. 大约有15种物品,但我不知道它们到底有多少。 I want to collect all items on this array. 我想收集此阵列上的所有项目。 How can I do that ? 我怎样才能做到这一点 ? While or something else? 一会儿还是其他?
I hope you will able to understand my problem. 希望您能理解我的问题。 I don't know English very well. 我不太会英语。
I want to collect all items on this array. 我想收集此阵列上的所有项目。 How can i do that ? 我怎样才能做到这一点 ? while or something else? 一会儿还是其他?
Iterate through every element in the Array
using a for-each
: 使用for-each
遍历Array
每个元素:
for(Integer i : array){
//Do whatever you want to do
}
That loop is either called a for-each
or advanced for-loop
. 该循环称为for-each
或advanced for-loop
。 It will iterate through every Object
in your array and returns that object (In your case, Integer i
) 它将遍历数组中的每个Object
并返回该对象(在您的情况下为Integer i
)
OR 要么
Use a regular for-loop. 使用常规的for循环。 You probably used it before so it will be easier for you - 您可能以前曾使用过它,因此对您来说会更容易-
for(int i = 0; i < array.size(); i++) {
Integer item = array.get(i);
}
To implicitly tackle your code, I will be assuming: 为了隐式地处理您的代码,我将假设:
If there's something I'm missing please correct me. 如果有什么我想念的,请纠正我。
ArrayList<Integer> array = new ArrayList<Integer>();
Integer tempInteger;
try{
tempInteger = Integer.parseInt(edittext.getText().toString());
}catch(NumberFormatException e){
e.printStackTrace();
}
array.add(tempInteger);
/*
* Once you have your array filled with 'elements' (In your case
* with Integer values) you can use the following loop called a
* 'for-each' loop to loop through ALL the elements in your list.
*/
for(Integer i : array){
System.out.println("array["+array.get(i)+"]" + " = " + i);
}
OR 要么
Using a regular for-loop
: 使用常规的for-loop
:
for(int i = 0; i < array.size() - 1; i++){
Integer myInteger = array.get(i);
System.out.println("array["+i+"]" + " = " + myInteger);
}
Hope I understand the question correct. 希望我理解正确的问题。 To get each item in array you may do the following: 要获取数组中的每个项目,您可以执行以下操作:
for(int i = 0; i < array.size(); i++)
{
Integer item = array.get(i);
//do whatever you want with item
}
Here is how to find a sum of all items in array: 这是如何查找数组中所有项目的总和:
Integer sum = 0;
for(int i = 0; i < array.size(); i++)
{
sum += array.get(i);
}
//sum is now contains sum of all items
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.