Arrays.asList method is used to returns an instance of List directly from given array. However, this instance is fixed-size and it means that you can't modify the List structure by adding one more element or removing the existing one. All of these operations will thrown an exception.
How to achieve that ? The simplest way is to use asList method:
public class AsListTest { @Test public void addAndFail() { String[] lettersArray = {"A", "B", "C"}; List<String> letters = Arrays.asList(lettersArray); assertTrue("Generated List should have 3 elements but has "+letters.size(), letters.size() == 3); // an exception should be thrown try { letters.add("D"); } catch (Exception e) { e.printStackTrace(); } assertTrue("Generated List should still have 3 elements but has "+letters.size() + " after adding", letters.size() == 3); // another exception should be thrown try { letters.remove(0); } catch (Exception e) { e.printStackTrace(); } assertTrue("Generated List should still have 3 elements but has "+letters.size()+ " after removing", letters.size() == 3); // edit existing element try { letters.add(0, "0"); } catch (Exception e) { e.printStackTrace(); } assertTrue("First element should be 'A' but was '"+letters.get(0)+"'", letters.get(0).equals("A")); } }
They're another way to create fixed-size List ? In standard Java environment no, but Apache Commons project provides a special object, org.apache.commons.collections.list.FixedSizeList. This object behaves exactly at the same manner as the list created with Arrays.asList method. So, it prevents against any modifications inside the list.