6

I'm trying to do the following in Java:

String pageName = "MyPage";
String pageSpace= "SpaceA.SpaceB";
List<String> spaceList = new ArrayList<String>();
String[] spaceArr = pageSpace.split("\\.");
spaceList = Arrays.asList(spaceArr);
spaceList.add(pageName);

Why am I not able to add a string to the list? I can do spaceList.get(0) and spaceList.get(1) which returns "SpaceA" and "SpaceB" but spaceList.get(2) fails which should return "MyPage".

3 Answers 3

8

Arrays.asList returns a List of a fixed size that is backed by the array passed to it. You can't add/remove elements to/from that List.

You shouldn't even be able to reach the spaceList.get(2) statement, since spaceList.add(pageName) should throw UnsupportedOperationException first (perhaps you caught that exception).

To overcome that, create a new ArrayList :

spaceList = new ArrayList<String>(Arrays.asList(spaceArr));
Sign up to request clarification or add additional context in comments.

Comments

1

To add more, Arrays.asList returns an instance of AbstractList with no implementation for add method, because of that you will recieve an UnsupportedOperationException from the AbstractList

Comments

0

Arrays.asList does not give you the instance of java.util.ArrayList, instead it gives the object of its own AbstractList implementation which is static inner class within Arrays class:

private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, Serializable { }

Though you can sort, iterate on the return List, it does not support add / remove kind of operations.

You might be looking for something discussed here : Converting String array to java.util.List

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.