Java ArrayList object creation best practice

Sometimes we can get java.lang.UnsupportedOperationException due to the bad coding practice while using Array. We can create ArrayList in multiple ways, here one thing we need to remind as new ArrayList<>() there is no fixed size and Arrays.asList(“test”) has the fixed size. Whenever we creates arrayList using Arrays.asList and appending another values will get ava.lang.UnsupportedOperationException.

Example here

package vinodvino;

 

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

 

public class ArrayTest {

 

public static void main(String args[]) {

    

List<String> firstArray=new ArrayList<>();

firstArray.add("Vinod");

firstArray.add("Shaji");

    System.out.println("FirstArrayValues"+firstArray);

 

 

List<String> secondArray=Arrays.asList("Vinod");

    secondArray.add("Shaji");

    System.out.println("SecondArrayValues"+secondArray);

 

 

}

}

 

Output

FirstArrayValues[Vinod, Shaji]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at vinodvino.ArrayTest.main(ArrayTest.java:19)

 

In order to avoid this we can use array as 

 

List<String> secondArray=new ArrayList<>(Arrays.asList("Vinod"));

 

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts