在Java开发中,经常需要在数组(Array)和列表(List,尤其是ArrayList)之间进行转换。无论是从数据库查询返回的数组,还是处理用户输入的数据,掌握Java数组转列表和列表转数组的方法都至关重要。本教程将手把手教你如何实现这些转换,即使你是编程小白,也能轻松上手!
数组是固定长度的,一旦创建就不能改变大小;而List(如ArrayList)是动态的,可以随时添加或删除元素。因此,在实际开发中:
ArrayList。List时,就需要反向转换。Java提供了多种方式将数组转换为List,最常用的是使用Arrays.asList()方法和Java 8的Stream API。
Arrays.asList()import java.util.*;public class ArrayToListExample { public static void main(String[] args) { String[] fruits = {"苹果", "香蕉", "橙子"}; // 使用 Arrays.asList() 转换 List<String> fruitList = Arrays.asList(fruits); System.out.println(fruitList); // 输出: [苹果, 香蕉, 橙子] }}
注意:Arrays.asList() 返回的是一个固定大小的列表,不能添加或删除元素(会抛出UnsupportedOperationException)。如果需要可变列表,请使用下面的方法。
new ArrayList<>(Arrays.asList())String[] fruits = {"苹果", "香蕉", "橙子"};// 创建一个可变的 ArrayListList<String> fruitList = new ArrayList<>(Arrays.asList(fruits));// 现在可以自由添加元素fruitList.add("葡萄");System.out.println(fruitList); // 输出: [苹果, 香蕉, 橙子, 葡萄] String[] fruits = {"苹果", "香蕉", "橙子"};List<String> fruitList = Arrays.stream(fruits) .collect(Collectors.toList());// 同样是可变列表fruitList.add("芒果");System.out.println(fruitList); // 输出: [苹果, 香蕉, 橙子, 芒果] 将List转换回数组也非常简单,主要使用List.toArray()方法。
toArray(new Type[0])List<String> fruitList = Arrays.asList("苹果", "香蕉", "橙子");// 转换为 String 数组String[] fruits = fruitList.toArray(new String[0]);System.out.println(Arrays.toString(fruits)); // 输出: [苹果, 香蕉, 橙子] 这是最安全、最推荐的方式。传入new String[0]可以让JVM自动分配合适大小的数组。
// 不推荐:容易出错String[] fruits = new String[fruitList.size()];fruitList.toArray(fruits); 这种方式需要手动指定数组大小,容易因大小不匹配导致问题,建议优先使用方法1。
int[])不能直接用Arrays.asList(),因为泛型不支持基本类型。应使用包装类(如Integer[])或Stream API配合mapToInt()等方法。List如果是通过Arrays.asList()创建的,是不可变的,尝试修改会抛异常。null)检查,避免程序崩溃。通过本教程,你已经掌握了在Java中进行数组与列表互转的核心方法。无论是使用Arrays.asList()、构造ArrayList,还是利用Java 8的Stream API,都能灵活应对各种开发场景。记住关键点:
new ArrayList<>(Arrays.asList(array))list.toArray(new Type[0])希望这篇关于Java数组转列表和ArrayList转换的教程对你有帮助!动手实践一下吧,编程能力就是在一次次练习中提升的。
本文由主机测评网于2025-12-08发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025124576.html