我们可以在 Java 中将数组转换为列表并转换回来吗?

javaobject oriented programmingprogramming更新于 2024/12/31 0:12:17

List 提供了两种将 List 转换为 Array 的方法。

1. 使用不带参数的 toArray() 方法。

Object[] toArray()

返回

包含此列表中所有元素的数组,且顺序正确。

2. 使用带有数组的 toArray()。

<T> T[] toArray(T[] a)

类型参数

  • T  −数组的运行时类型。

参数

  • a  − 如果数组足够大,则为用于存储此列表元素的数组;否则,将为此目的分配相同运行时类型的新数组。

返回

包含此列表元素的数组。

抛出

  • ArrayStoreException − 如果指定数组的运行时类型不是此列表中每个元素的运行时类型的超类型。

  • NullPointerException −如果指定的数组为空。

为了将数组转换为列表,我们可以使用 Arrays.asList() 方法获取包含数组所有元素的列表。

public static <T> List<T> asList(T... a)

类型参数

  • T  − 元素的运行时类型。

参数

  • a  −将支持列表的数组。

返回

指定数组的列表视图。

示例

以下示例展示了 toArray() 和 Arrays.asList() 方法的用法 −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      Integer[] array = {1, 2, 3, 4, 5};

      // 数组到列表的转换
      List<Integer> list = new ArrayList<>(Arrays.asList(array));
      System.out.println("List: " + list);

      // 列表到数组的转换
      Object[] items = list.toArray();
      for (Object object : items) {
         System.out.print(object + " ");
      }
      System.out.println();

      // 列表到数组的转换
      Integer[] numbers = list.toArray(new Integer[0]);
      for (int number : numbers) {
         System.out.print(number + " ");
      }
   }
}

输出

这将产生以下结果 −

List: [1, 2, 3, 4, 5]
1 2 3 4 5
1 2 3 4 5

相关文章


有用资源