Home > Enterprise >  How can I create a Java List/Map/Collection in which I can modify the values but not add nor remove
How can I create a Java List/Map/Collection in which I can modify the values but not add nor remove

Time:08-12

I want to create some sort of list where I can modify the values of the objects inside but not be able to add to it nor remove from it once it is initialized. Is this possible? If so, how can I do it?

CodePudding user response:

If the types of objects stored in a List (or any Collection) are mutable, then the first part of your question is inherent to how Java collections and object references work. Just because an object is contained in a collection doesn't put any restrictions on what I can do with (or _to) that object.

Having said that, if the objects in the list are not mutable (eg, String, LocalDate, or some other value object), there’s nothing you can do to modify them.

Unmodifiable list

As for the second part, you want an unmodifiable collection, and for that you can simply create one using java.util.Collections.unmodifiableList(List<? extends T>). Or in Java 9 , use List.of or List.copyOf to make an unmodifiable list.

Fixed size list

If what you want is a List that can not be added to or removed from, but can have individual elements replaced, then consider third-party libraries:

CodePudding user response:

implement some Collection interface, create variable of Collection implementation, and override add, remove and get methods. For example:

class myCollection implements List{
private List<Integer> list =new ArrayList<>(); 

public  myCollection (Collection col){
list.addAll(col);
}
@Override
Integer get(int i){
return list.get(i);
}
@Override
void remove(int i){
//empty so you cant remove anything
}
}     

hope you got an idea

  • Related