Never put unrelated objects into your collections. Assuming that apple and chair are unrelated (they don't have the same parent or share an interface),
you should never do this:
Apple apple = new Apple();
Chair chair = new Chair();
List list = new ArrayList();
list.add(apple);
list.add(chair);
This gets very difficult to work with. You'll likely have to use a lot of if/else if/else statements, each containing an instanceof operator
if you want to work with this list. Here is a more concrete example. I once saw some code that was doing this:
Map map = new HashMap();
...
public void put(String key, String value) {
String existingValue = map.get(key);
if (existingValue == null) {
map.put(key, value);
} else { //a value is already in the map
if (existingValue instanceof List) {
((List) existingValue).add(value);
} else { //the existingValue is a String
map.remove(key);
List list = new ArrayList();
list.add(existingValue); //put the value that was there in the list
list.add(value); //also add the new value
map.put(key, list);
}
}
}The put method adds the value to the map, but if there is already a value associated with that key, it puts the value in a List.
If there isn't a value associated with that key, it adds the value directly as a String.
This is very difficult to work with. If you call the get(key) method, you have to do an if statement to check if you've gotten a String or a List and
then act appropriately. Here is a better way to write this code:
Map<List<String>> map = new HashMap<List<String>>();
...
public void put(String key, String value) {
List existingValue = map.get(key);
if (existingValue == null) {
List<String> list = new ArrayList<String>();
list.add(value);
map.put(key, list);
} else { //a value is already in the map
existingValue.add(value);
}
}This put method doesn't care if the key has 1 or multiple values associated with it; it returns a List regardless. As a result, when you deal with the get(key)
method, it doesn't require a bunch of if statements to discover what result was returned to you. You can just assume it's a List.
don_t_put_different_types_in_your_collections, Rev. 2, Last changed on 2008-01-09 21:02, 122 page hits