Skip to content

Instantly share code, notes, and snippets.

@natemort
Last active October 17, 2016 20:32
Show Gist options
  • Select an option

  • Save natemort/d677d35f6fe7e8f4a782b496b6695fe2 to your computer and use it in GitHub Desktop.

Select an option

Save natemort/d677d35f6fe7e8f4a782b496b6695fe2 to your computer and use it in GitHub Desktop.
import java.util.Map;
import java.util.HashMap;
class Java {
public static void main(String[] args) {
// Associate(or map) string values to numbers(Integerrs)
Map<String, Integer> map = new HashMap<String, Integer>();
// map["joe"] = 1;
map.put("Joe", 1);
map.put("Nate", 2);
// joe = 1, nate = 2
int joe = map.get("Joe");
int nate = map.get("Nate");
// Say we have a bunch of integers from 1 to 10^31 -1(the max value of integers in java)
// If we create an array of that size, we'll be using a minimum of 68 GB of RAM.
// If we only have two values that need to be associated(0 and 10^31 -1), it would be
// impossible to do with an array. However, we can do with with a map, and while the memory
// usage isn't as direcly predictable(maps are complicated to write), it will probably use less than
// 100 bytes
// When dealing with generics you can use <> to avoid repeating yourself(Java 7+)
Map<Integer, String> map2 = new HashMap<>();
map2.put(1, "Joe");
map2.put(2, "Nate");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment