admin 管理员组

文章数量: 1086019


2024年1月11日发(作者:css3选择器优先级顺序)

java中遍历的用法

在 Java 中,遍历是指对集合、数组、列表等数据结构中的元素进行逐个访问和处理的操作。以下是几种常见的遍历用法:

1. **使用`for`循环遍历数组:**

```java

public class Main {

public static void main(String[] args) {

int[] array = {10, 20, 30, 40, 50};

for (int i = 0; i < ; i++) {

n(array[i]);

}

}

}

```

在上述示例中,使用`for`循环遍历数组`array`,并打印每个元素的值。

2. **使用`while`循环遍历数组:**

```java

public class Main {

public static void main(String[] args) {

int[] array = {10, 20, 30, 40, 50};

int i = 0;

while (i < ) {

n(array[i]);

i++;

}

}

}

```

在这个示例中,使用`while`循环来遍历数组`array`,并打印每个元素的值。

3. **使用`for-each`循环遍历数组:**

```java

public class Main {

public static void main(String[] args) {

int[] array = {10, 20, 30, 40, 50};

for (int element : array) {

n(element);

}

}

}

```

在这个示例中,使用`for-each`循环遍历数组`array`,并打印每个元素的值。

4. **使用`for`循环遍历集合:**

```java

import ist;

import ;

public class Main {

public static void main(String[] args) {

List list = new ArrayList<>();

("Apple");

("Banana");

("Orange");

for (int i = 0; i < (); i++) {

n((i));

}

}

}

```

在这个示例中,使用`for`循环遍历集合`list`,并打印每个元素的值。

5. **使用`Iterator`遍历集合:**

```java

import ist;

import or;

import ;

public class Main {

public static void main(String[] args) {

List list = new ArrayList<>();

("Apple");

("Banana");

("Orange");

Iterator iterator = or();

while (t()) {

String element = ();

n(element);

}

}

}

```

在这个示例中,使用`Iterator`来遍历集合`list`,并打印每个元素的值。

以上是一些常见的遍历用法示例,你可以根据实际需求选择适合的遍历方式来处理数组、集合或其他数据结构中的元素。


本文标签: 遍历 循环 数组 选择器 集合