Reputation: 107
I have a BeanMap representing an object, one of the fields of this object is a List and I would like to be able to add to this. At the minute the code will simply take an existing list and put the full list into the BeanMap. But if I want to add items to the list later on they override the items that were there as a new list is being put into the BeanMap.
So far I've tried getting the List from the BeanMap but it will not allow me to use the beanMap.get method and assign a new string to this return result. You can do so for a Object though.
I also tried getting it an as object and using Arrays.asList() to manipulate it. But this did not work either.
What I've currently tried:
Object listObject = myBeanMap.get("theList");
Arrays.asList(listObject).add("SOME STRING");
myBeanMap.put("theList", listObject);
I'm looking for a way to add items to that list whilst keeping the currently existing ones.
Upvotes: 0
Views: 152
Reputation: 5348
Arrays.asList(listObject).add("SOME STRING");
Arrays.asList
creates a new list, you add something to it, but you never save the list, so you can't add new things. You need to change your code to this:
List<Object> list = Arrays.asList(listObject, "SOME STRING");
myBeanMap.put("theList", list);
You can't use add()
method because the list implementation returned by Arrays.asList()
does not support add()
and you'll get a runtime exception. That's why you have to put the new items you want as arguments for Arrays.asList()
call.
Edit 1:
If the listObject
is already a list instance, e.g. a list of strings, you can add one more by casting it first:
List<String> list = (List<String>) myBeanMap.get("theList");
list.add("another string");
myBeanMap.put("theList", list);
Edit 2: If you want to preserve the original list, you need to copy the old list:
List<String> original = (List<String>) myBeanMap.get("theList");
List<String> extended = new ArrayList<>(original);
extended.add("new string"); // "new string" is NOT added to the original list
myBeanMap.put("theExtendedList", extended);
Upvotes: 2