您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 Java 中,你可以使用 Enhanced For Loop(也称为 for-each 循环)来遍历数组和集合
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayToCollection {
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5};
// 将数组转换为集合
List<Integer> collection = new ArrayList<>();
for (Integer element : array) {
collection.add(element);
}
System.out.println("Array: " + Arrays.toString(array));
System.out.println("Collection: " + collection);
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CollectionToArray {
public static void main(String[] args) {
List<Integer> collection = new ArrayList<>();
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(4);
collection.add(5);
// 将集合转换为数组
Integer[] array = collection.toArray(new Integer[0]);
System.out.println("Collection: " + collection);
System.out.println("Array: " + Arrays.toString(array));
}
}
在这两个示例中,我们使用了 Enhanced For Loop 来遍历数组和集合的元素。在第一个示例中,我们将数组中的每个元素添加到集合中。在第二个示例中,我们将集合中的每个元素添加到数组中。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。