Home  >  Article  >  Java  >  How to create a list with values ​​in Java?

How to create a list with values ​​in Java?

WBOY
WBOYforward
2023-08-25 18:52:411320browse

How to create a list with values ​​in Java?

We can use the Arrays.asList() method to get a list of specified elements in a single statement.

Syntax

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

Returns a fixed-size list backed by the specified array. (Changing the returned list "writes" the array.)

Type parameter

  • T − The runtime type of the array.

Parameters

  • a - Array that supports lists.

Returns a list view of the specified array

In case we use Arrays.asList() then we cannot add/remove from the list element. Therefore, we use this list as input to the ArrayList constructor to ensure that the list is modifiable.

Example

The following example demonstrates how to create a list declaration that contains multiple items in a single list.

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {

      // Create a list object
      List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

      // print the list
      System.out.println(list);

      list.add(4);
      System.out.println(list);
   }
}

Output

This will produce the following results -

[1, 2, 3]
[1, 2, 3, 4]

The above is the detailed content of How to create a list with values ​​in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete