Search code examples
javaeclipsecollectionshashmapunmodifiable

Adding element from unmodifiable list to map


I'm not sure if I'm trying to do something stupid here, but I cannot quite find any fitting information on this matter. I'm getting a List via Collections.unmodifiableList(MyList) from a remote location. I then want to add the received Elements into a a Map for buffering. Weirdly Eclipse won't let me add the desired objects to the map, and states that the add method is not defined for the Map I've created. To be more accurate, here is a representative code of my problem:

import java.util.Collection;
import java.util.List;
import java.util.Map;

private Map<String,MyElement> buffer = new HashMap<String,MyElement>();

private void receiveElements(){
    List<myElement> myList= Collections.unmodifiableList(remoteService.getElements());
    for(myElement e:myList){
       buffer.add(e.getId(),e);
    }
}

In the line I try to add the object to the buffer the add function is underlined and it tells me:

The method add(String, myElement) is undefined for the type Map<String,myElement>

Is this related to my temporal list being unmodifiable? I only want to read information from the elements in the map anyway.

Thanks in advance!


Solution

  • On the Map interface the method add doesn't exist, you should use put

    buffer.put(e.getId(), e);