Monday 18 April 2016

How to declare and initialize a List (ArrayList and LinkedList) with values in Java mkniit.blogspot.in

Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs e.g. collection literals, but there is a trick which allows you to declare and initialize a List at the same time. This trick is also known as initializing List with values. If you have been using Java programming language for quite some time then you must be familiar with syntax of array in Java and how to initialize an array in the same line while declaring it as shown below:

String[] oldValues = new String[] {"list" , "set" , "map"};

or even shorter :

String[] values = {"abc","bcd", "def"};

Similarly, we can also create List  and initialize it at the same line, popularly known asinitializing List in one line exampleArrays.asList() is used for that purpose which returns a fixed size List backed by Array. By the way don’t confuse between Immutable or read only List which doesn’t allow any modification operation including set(index)which is permitted in fixed length List.Here is an example of creating and initializing Listin one line:


Java program to Create and initialize List in one line

How to create and initialize List in one line in Java with ArrayHere is a Java program which creates and initialize List in one line using Array.Arrays.asList() method is used to initialize List in one line and it takes an Array which you can create at the time of calling this method itself.Arrays.asList() also use Generics to provide type-safety and this example can be written using Generics as well.


import java.util.Arrays;
import java.util.List;

/**
 * How to create and initialize List in the same line,
 * Similar to Array in Java.
 * Arrays.asList() method is used to initialize a List
 * from Array but List returned by this method is a
 * fixed size List and you can not change its size.
 * Which means adding and deleting elements from the
 * List is not allowed.
 *
 * @author Javin Paul
 */

public class ListExample {

    public static void main(String args[]) {
 
      //declaring and initializing array in one line
      String[] oldValues = new String[] {"list" , "set" , "map"};
      String[] values = {"abc","bcd""def"};
 
      //initializing list with array in java
      List init = Arrays.asList(values);
      System.out.println("size: " + init.size()
                          +" list: " + init);
 
      //initializing List in one line in Java
      List oneLiner = Arrays.asList("one" , "two""three");
      System.out.println("size: " + init.size()
                       +" list: " + oneLiner);
 
      // List returned by Arrays.asList is fixed size
      // and doesn't support add or remove


      // This will throw java.lang.UnsupportedOperationException
      oneLiner.add("four"); 


      // This also throws java.lang.UnsupportedOperationException
      //oneLiner.remove("one"); 
    }
}

Output:
size: 3 list: [abc, bcd, def]
size: 3 list: [one, two, three]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:131)
        at java.util.AbstractList.add(AbstractList.java:91)
        at test.ExceptionTest.main(ExceptionTest.java:32)

As shown in above example it's important to remember that List returned byArrays.asList() can not be used as regular List for further adding or removing elements. It's kind of fixed length Lists which doesn't support addition and removal of elements. Nevertheless its clean solution for creating and initializing List in Java in one line, quite useful for testing purpose.

If you want to convert that fixed length List into a proper ArrayList, LinkedList or Vector any other Collection class you can always use the copy constructor provided by Collection interface, which allows you to pass a collection while creating ArrayList or LinkedList and all elements from source collection will be copied over to the new List. This will be the shallow copy so beware, any change made on an object will reflect in both the list.

How to declare and initialize a List in one line


Here is how you can convert this fixed length list to ArrayList or LinkedList in Java:

package beginner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


/**
 * Java Program to create and initialize ArrayList LinkedList in same line
 * 
 * @author WINDOWS 8
 *
 */
public class HelloWorldApp {

    public static void main(String args[]) {
      
        List<String> pairs = Arrays.asList(new String[]{"USD/AUD", "USD/JPY", "USD/EURO"});
        ArrayList<String> currencies = new ArrayList<>(pairs);
        LinkedList<String> fx = new LinkedList<>(pairs);
        
        System.out.println("fixed list: " + pairs);
        System.out.println("ArrayList: " + currencies);
        System.out.println("LinkedList: " + fx);
    }
}

Output:
fixed list: [USD/AUD, USD/JPY, USD/EURO]
ArrayList: [USD/AUD, USD/JPY, USD/EURO]
LinkedList: [USD/AUD, USD/JPY, USD/EURO]

This is pretty neat and I always this trick you create the Collection I want with values. You can use this to create ArrayList with values, Vector with values, or LinkedList with values. In theory, you can use this technique to create any Collection with values.

Related Java Collection tutorials from Javarevisited Blog
Difference between LinkedList and ArrayList in Java



RELATED TOPICS

No comments:

Post a Comment