java arraylist 初始化_ArrayList初始化的4种方法

In the last post we discussed about class ArrayList in Javaand it’s important methods. Here we are sharing multiple ways to initialize an ArrayList with examples.

Method 1: Initialization using Arrays.asList

Syntax:

ArrayList obj = new ArrayList(

Arrays.asList(Object o1, Object o2, Object o3, ....so on));

Example:

import java.util.*;

public class InitializationExample1 {

public static void main(String args[]) {

ArrayList obj = new ArrayList(

Arrays.asList("Pratap", "Peter", "Harsh"));

System.out.println("Elements are:"+obj);

}

}

Output:

Elementsare:[Pratap,Peter,Harsh]

Method 2: Anonymous inner class method to initialize ArrayList

Syntax:

ArrayList obj = new ArrayList(){{

add(Object o1);

add(Object o2);

add(Object o3);

...

...

}};

Example:import java.util.*;public classInitializationExample2 {public static voidmain(String args[]) {

ArrayList cities = new ArrayList(){{

add("Delhi");

add("Agra");

add("Chennai");

}};

System.out.println("Content of Array list cities:"+cities);

}

}

Output:

Contentof Arraylist cities:[Delhi,Agra,Chennai]

Method3: Normal way of ArrayList initialization

Syntax:

ArrayList obj = new ArrayList();

obj.add("Object o1");

obj.add("Object o2");

obj.add("Object o3");

...

...

Example:import java.util.*;public classDetails {public static voidmain(String args[]) {

ArrayList books = new ArrayList();

books.add("Java Book1");

books.add("Java Book2");

books.add("Java Book3");

System.out.println("Books stored in array list are: "+books);

}

}

Output:

Booksstored inarray list are:[JavaBook1,JavaBook2,JavaBook3]

Method 4: Use Collections.ncopies

Collections.ncopies method can be used when we need to initialize the ArrayList with the same value for all of its elements. Syntax: count is number of elements and element is the item value

ArrayList obj = new ArrayList(Collections.nCopies(count, element));

Example:import java.util.*;public classDetails {public static voidmain(String args[]) {

ArrayList intlist = new ArrayList(Collections.nCopies(10, 5));

System.out.println("ArrayList items: "+intlist);

}

}

Output:

ArrayListitems:[5,5,5,5,5,5,5,5,5,5]

写博客是为了记住自己容易忘记的东西,另外也是对自己工作的总结,文章可以转载,无需版权。希望尽自己的努力,做到更好,大家一起努力进步!

如果有什么问题,欢迎大家一起探讨,代码如有问题,欢迎各位大神指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值