Explain Codes LogoExplain Codes Logo

Convert String array to ArrayList

java
best-practices
collections
java-8
Anton ShumikhinbyAnton Shumikhin·Oct 19, 2024
TLDR

To convert a String array to a ArrayList, use Arrays.asList() itself inside a new expression for ArrayList:

// Yes, writing your favorite tongue twisters can be this easy! String[] stringArray = {"how", "can", "a", "clam", "cram", "in", "a", "clean", "cream", "can"}; ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(stringArray));

This ArrayList contains elements from stringArray and supports dynamic operations such as additions and removals.

Converting an array (including special cases)

Handling null values

When your array includes null values, the standard method handles them without errors, giving a place for null too in the ArrayList:

// Everyone is welcome, even null. String[] stringArrayWithNulls = {"I'm", null, "Null"}; ArrayList<String> arrayListWithNulls = new ArrayList<>(Arrays.asList(stringArrayWithNulls));

Modifiable vs Non-modifiable lists

Arrays.asList() returns a fixed-size list, so you cannot manipulate this list's size. Encapsulate it with new ArrayList<>(), and the list becomes mutable:

// Show Non-modifiable List its rightful place, just a bridge to an ArrayList List<String> fixedSizeList = Arrays.asList(stringArray); ArrayList<String> extendableList = new ArrayList<>(fixedSizeList);

Considerations for efficiency

Although Arrays.asList() is efficient, wrapping an ArrayList introduces an extra step that might affect performance depending on the context.

When should Array and ArrayList be Used?

Whether to use Array or ArrayList is determined by your specific needs. The Array may be the better choice if the collection is fixed and you often use operations like sorting or binary search, whereas ArrayList is ideal for dynamic data.

A different avenue with Collections.addAll()

If adding elements to an existing ArrayList, Collections.addAll() might be a smoother path:

ArrayList<String> list = new ArrayList<>(); Collections.addAll(list, stringArray);

Skipping List creation via Arrays.asList() may prove to be more efficient and gives us the desired mutability.

Neat integration and best practices

Always strive to interweave your solutions with existing code neatly while clinging to Java best practices. Use generics correctly to thwart ClassCastException, and always guard your code with thorough testing to ensure reliability and durability.