Java Generic Collection Contains – Use A Map You Fool!

This post is hopefully going to serve as a reminder for myself, if nothing else.

Today I was faced with a problem of having created a collection using a handcrafted (but very simple!) object. I then had a String array which I wanted to use to find out if an entry was in my collection or not. So to briefly summarise:

public class Employee {

   private String name;
   private int age;
   private int phoneNumber;

   public Employee(String newName, int newAge, int phone) {
      name = newName;
      age = newAge;
      phoneNumber = phone;

   public class Main {

       public void myMethod() {
          List<Employee> employees = new ArrayList<Employee>();
          employees.add("Joe", 29, 2993);
          employees.add("Fred", 30, 4483);

          String[] employeeArr = new String[] {"Joe", "Fred", "Gary"};


So I’m basically trying to find out that Gary isn’t in my collection and add him with some default values.

I started out by looking at the employees.Contains() method, knowing deep down that this wasn’t the way to do things. I tried overriding the equals() method within the Employee object, but when it wanted to start bringing in a 2nd override for the hash() function, I knew this was wrong.

What I really needed, and it took a while to figure this out, was a Map. Using the name as the key for the map, I could then easily use the Map method .containsKey().

So the ‘contains’ code effectively changed to this:

Map<String, Employee> employees = new HashMap<String, Employee>();
employees.put("Joe", new Employee("Joe", 29, 2993));
employees.put("Fred", new Employee("Fred", 30, 4483));

String[] employeeArr = new String[] {"Joe", "Fred", "Gary"};

if (employees.size() != employeeArr.length) {
   for (int i = 0; i < employeeArr.length; i++) {
      if (!employees.containsKey(employeeArr[i])) {
         employees.put(employeeArr[i], new Employee(employeeArr[i], 0, 0));

Just to finish, I then wanted to output my map by iterating through it. The code for this is:

Collection c = employees.values();
Iterator itr = c.iterator();

while (itr.hasNext()) {
   Employee emp = (Employee);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s