📜  如何在Java中用指定值在单行中初始化列表?

📅  最后修改于: 2022-05-13 01:58:09.467000             🧑  作者: Mango

如何在Java中用指定值在单行中初始化列表?

给定一个值N ,任务是在Java中的一行中创建一个具有该值 N 的 List 。

例子:

Input: N = 5
Output: [5]

Input: N = GeeksForGeeks
Output: [GeeksForGeeks]

方法:

  • 获取值 N
  • 使用此值创建一个数组 N
  • 在构造函数中将此数组作为参数创建一个列表

下面是上述方法的实现:

// Java program to initialize a list
// in a single line with a specified value
  
import java.io.*;
import java.util.*;
  
class GFG {
  
    // Function to create a List
    // with the specified value
    public static  List createList(T N)
    {
  
        // Currently only one value is taken
        int size = 1;
  
        // Create an array of size 1
        T arr[] = (T[]) new Object[1];
  
        // Add the specified value in the array
        arr[0] = N;
  
        // System.out.println(Arrays.toString(arr));
        List list = Arrays.asList(arr);
  
        // return the created list
        return list;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        int N = 1024;
        System.out.println("List with element "
                           + N + ": "
                           + createList(N));
  
        String str = "GeeksForGeeks";
        System.out.println("List with element "
                           + str + ": "
                           + createList(str));
    }
}

输出:

List with element 1024: [1024]
List with element GeeksForGeeks: [GeeksForGeeks]