How can Java define a list and assign values to it?

In Java, you can use the ArrayList class to define and assign values to a list. Here is an example code:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // 定义一个列表
        ArrayList<Integer> list = new ArrayList<>();

        // 给列表赋值
        list.add(1);
        list.add(2);
        list.add(3);

        // 打印列表内容
        System.out.println("List elements: " + list);
    }
}

In this example, we first introduce the ArrayList class, then we define an ArrayList object ‘list’ in the main method, and use the add method to add elements 1, 2, and 3 to the list. Finally, we print the contents of the list using the System.out.println method.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds