Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize static ArrayList<myclass> in one line

Tags:

java

i have MyClass as

MyClass(String, String, int); 

i know about how to add to add to ArrayList in this way:

MyClass.name = "Name"; MyClass.address = "adress";adress MyClass.age = age; 

then add to arrayList like:

list.add(MyClass); 

but now i have many object MyClass in static form, i want to add

ArrayList<MyClass> list = new ArrayList<MyClass>({"Name","Address", age};.....); 

can i do like this. thank anyway

like image 303
Ngo Ky Avatar asked Oct 01 '12 09:10

Ngo Ky


People also ask

How do you initialize an ArrayList in one line?

Initialize ArrayList in one line To initialize an arraylist in single line statement, get all elements in form of array using Arrays. asList method and pass the array argument to ArrayList constructor. ArrayList<String> names = new ArrayList<String>( Arrays. asList( "alex" , "brian" , "charles" ) );

How do you initialize a list in Java in one line?

List<String> list = List. of("foo", "bar", "baz"); Set<String> set = Set. of("foo", "bar", "baz");

How do you create a static list in a String?

public static String[] list; We define String list as String[] and object name. list = new String[] { "One", "Two", "Three", "Four", "Five" }; Using for loop we need to fetch the values of list and print them to screen.


2 Answers

You can use double braces initialization: -

List<MyClass> list = new ArrayList<MyClass>() {     {         add(new MyClass("name", "address", 23));         add(new MyClass("name2", "address2", 45));     } }; 

As you can see that, inner braces is just like an initializer block, which is used to initialize the list in one go..

Also note the semi-colon at the end of your double-braces

like image 186
Rohit Jain Avatar answered Oct 09 '22 05:10

Rohit Jain


You can do

List<MyClass> list = Arrays.asList(                          new MyClass("Name", "Address", age),                          // many more                      ); 

Note: this will create a list where you can't change its size.

like image 45
Peter Lawrey Avatar answered Oct 09 '22 04:10

Peter Lawrey