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".
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With