Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List<string> not adding to list after Arrays.asList() has been used

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".

like image 440
Gerrie van Wyk Avatar asked Mar 14 '23 01:03

Gerrie van Wyk


1 Answers

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));
like image 150
Eran Avatar answered Mar 17 '23 03:03

Eran