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

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

WBOY
Release: 2023-08-25 18:52:41
forward
1342 people have browsed it

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)
Copy after login

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);
   }
}
Copy after login

Output

This will produce the following results -

[1, 2, 3]
[1, 2, 3, 4]
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template