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
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" ) );
List<String> list = List. of("foo", "bar", "baz"); Set<String> set = Set. of("foo", "bar", "baz");
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With