search
HomeJavajavaTutorialAn article explaining 8 ways to initialize a List collection in Java (with code)

In the previous article "A Brief Analysis of Server Code Deployment in Linux (Sharing)", we learned about server code deployment in Linux. The following article will give you an understanding of the 8 ways to initialize a List collection in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

An article explaining 8 ways to initialize a List collection in Java (with code)

List is a commonly used collection in development. The following are several ways to initialize List.

Normal way

List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("getList1: " + list);

Output

getList1: [1, 2, 3]

Arrays Tool Class

// 生成的list不可变
List<String> list = Arrays.asList("1", "2", "3");
System.out.println("getList2: " + list);
// 如果要可变需要用ArrayList包装一下
List<String> numbers = new ArrayList<>(Arrays.asList("1", "2", "3"));
numbers.add("4");
System.out.println("numbers: " + numbers);

Output

getList2: [1, 2, 3]
numbers: [1, 2, 3, 4]

Collections Tool Class

// 生成的list不可变
List<String> list = Collections.nCopies(3, "1");
System.out.println("getList3: " + list);
// 如果要可变需要用ArrayList包装一下
List<String> dogs = new ArrayList<>(Collections.nCopies(3, "dog"));
dogs.add("dog");
System.out.println("dogs: " + dogs);

Output

getList3: [1, 1, 1]
dogs: [dog, dog, dog, dog]

Lists Tool Class

List<String> list = Lists.newArrayList("1", "2", "3");
System.out.println("getList4: " + list);

Output

getList4: [1, 2, 3]

Anonymous inner class

List<String> list = new ArrayList<String>() {{
     add("1");
     add("2");
     add("3");
}};
System.out.println("getList5: " + list);

Output

getList5: [1, 2, 3]

ImmutableList

List<String> list = ImmutableList.of("1", "2", "3");
System.out.println("getList6: " + list);

Output

getList6: [1, 2, 3]

Java8 Stream

List<String> list = Stream.of("1", "2", "3").collect(Collectors.toList());
System.out.println("getList7: " + list);

Output

getList7: [1, 2, 3]

Java9 List.of

List<String> list = List.of{"1", "2", "3"};
System.out.println("getList8: " + list);

Output

getList8: [1, 2, 3]

Recommended learning: Java video tutorial

The above is the detailed content of An article explaining 8 ways to initialize a List collection in Java (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:禅境花园. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.