Skip to content

Instantly share code, notes, and snippets.

@jerolba
Created August 5, 2019 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerolba/070c725b96ee8178492815d93f87a7a3 to your computer and use it in GitHub Desktop.
Save jerolba/070c725b96ee8178492815d93f87a7a3 to your computer and use it in GitHub Desktop.
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