Java程序将数组转换为列表
java.util包的Arrays类提供了一种称为的方法asList()。此方法接受数组作为参数,然后返回List对象。要将数组转换为List对象-
创建一个数组或从用户那里读取它。
使用asList()Arrays类的方法将数组转换为列表对象。
打印列表对象的内容。
示例
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class ArrayToList {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array to be created ::");
int size = sc.nextInt();
String [] myArray = new String[size];
for(int i=0; i<myArray.length; i++){
System.out.println("Enter the element "+(i+1)+" (String) :: ");
myArray[i]=sc.next();
}
List<String> list = Arrays.asList(myArray);
System.out.println("Given array is converted to a list");
System.out.println("Contents of list ::"+list);
list.toArray(myArray);
}
}输出结果
Enter the size of the array to be created :: 4 Enter the element 1 (String) :: Java Enter the element 2 (String) :: JavaFX Enter the element 3 (String) :: WebGL Enter the element 4 (String) :: JoGL Given array is converted to a list Contents of list ::[Java, JavaFX, WebGL, JoGL]
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短