java使用foreach遍历输出包含1-10的数组
时间: 2023-11-27 20:49:29 浏览: 38
可以使用以下代码:
```java
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int num : arr) {
System.out.println(num);
}
```
这段代码会遍历数组 `arr` 中的每一个元素,并输出到控制台中。
相关问题
java 使用foreach遍历ArrayList<String>数组
使用foreach循环遍历`ArrayList<String>`数组的示例代码如下:
```
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
for (String fruit : list) {
System.out.println(fruit);
}
```
其中,`list`是`ArrayList<String>`类型的数组,`fruit`是在循环中代表每个元素的变量名,`for`循环遍历整个数组并输出每个元素的值。
输出结果如下:
```
Apple
Banana
Orange
```
需要注意的是,使用foreach循环遍历数组时,不能修改数组中的元素。如果需要修改元素,可以使用传统的for循环遍历数组并修改元素。
java 在foreach中使用Iterator遍历ArrayList<String>数组
在`foreach`循环中使用`Iterator`遍历`ArrayList<String>`数组的示例代码如下:
```
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}
```
其中,`list`是`ArrayList<String>`类型的数组,`iterator()`方法返回一个`Iterator`对象,`while`循环遍历整个数组并输出每个元素的值。
输出结果如下:
```
Apple
Banana
Orange
```
需要注意的是,在使用`Iterator`遍历数组时,可以通过`iterator.remove()`方法删除元素,但不能使用`list.remove()`方法删除元素,否则会抛出`ConcurrentModificationException`异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)