0

I have the following code:

public void parseAttribs(String attribs){

   //attribs is a comma separated list
   //we are making a List from attribs by splitting the string at the commas

   List<String> attributes = Arrays.asList(attribs.split("\\s*,\\s*"));

   //when I try to add an element to the attributes List if fails
   attributes.add("an element");

I've found this Unable to add a String to an ArrayList: "misplaced construct(s)" and tried to create a sub-class but I had to pass the List to the subclass as well and it still didn't work.

Could anyone please shed some light on this?

Many thanks

1
  • Thanks Reimeus and Rangi Lin. It works with your suggestion. Commented Mar 11, 2013 at 15:06

2 Answers 2

9

Arrays.asList returns a fixed-sizeList. You could use

new ArrayList<String>(Arrays.asList(...)))

This will give you a List where elements can be added.

Sign up to request clarification or add additional context in comments.

Comments

6

This code will not works because the list returned by Arrays.asList() is an immutable list.

You can construct from an ArrayList constructor to make it works.

List<String> attributes = new ArrayList<String>(Arrays.asList(attribs.split("\\s*,\\s*")));

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.