Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of potential bugs using incorrectly Map API
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class MapViews {
public static void main(String[] args) {
mapChangeModifiesValuesSet();
mapChangeModifiesKeysSet();
valuesSetChangeModifiesMap();
}
static void mapChangeModifiesValuesSet() {
Map<Integer, User> usersMap = loadUsersFromWherever();
UseValues withValues = new UseValues(usersMap.values());
usersMap.put(4, new User(4, "Donald"));
withValues.doSomething();
}
static UseKeys mapChangeModifiesKeysSet() {
Map<Integer, User> usersMap = loadUsersFromWherever();
UseKeys withKeys = new UseKeys(usersMap.keySet());
usersMap.put(4, new User(4, "Donald"));
withKeys.doSomething();
return withKeys;
}
static void valuesSetChangeModifiesMap() {
Map<Integer, User> usersMap = loadUsersFromWherever();
UseValues withValues = new UseValues(usersMap.values());
withValues.clear();
System.out.println("Map content: " + usersMap);
}
static class UseValues {
private final Collection<User> users;
public UseValues(Collection<User> users) {
this.users = users;
System.out.println("UseValues constructor: " + users);
}
public void doSomething() {
System.out.println("UseValues doSomething: " + users);
}
public void clear() {
users.clear();
}
}
static class UseKeys {
private final Collection<Integer> ids;
public UseKeys(Collection<Integer> ids) {
this.ids = ids;
System.out.println("UseKeys constructor: " + ids);
}
public void doSomething() {
System.out.println("UseKeys doSomething: " + ids);
}
}
static class User {
private final Integer id;
private final String name;
public User(Integer i, String name) {
this.id = i;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return id + ": " + name;
}
}
static Map<Integer, User> loadUsersFromWherever() {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User(1, "John"));
users.put(2, new User(2, "Peter"));
users.put(3, new User(3, "Rose"));
return users;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.