Using Custom Objects in Sets and as Map Keys: Java Collections Framework Video Tutorial, Part 6

A tutorial on using your own objects as keys in Maps or in Sets. To use your own objects as keys in Maps or in Sets you need to tell Java how to compare your objects, by implementing the hashCode() and equals() methods. Fortunately all decent IDEs will do this for you.

After starting the video, click the maximise button to make it fullscreen so you can see the code!

Code For This Tutorial

App.java:

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

class Person {
	private int id;
	private String name;
	
	public Person(int id, String name) {
		this.id = id;
		this.name = name;
	}
	
	public String toString() {
		return "{ID is: " + id + "; name is: " + name + "}";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Person other = (Person) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
}


public class App {

	public static void main(String[] args) {
		
		Person p1 = new Person(0, "Bob");
		Person p2 = new Person(1, "Sue");
		Person p3 = new Person(2, "Mike");
		Person p4 = new Person(1, "Sue");
		
		Map<Person, Integer> map = new LinkedHashMap<Person, Integer>();
		
		map.put(p1, 1);
		map.put(p2, 2);
		map.put(p3, 3);
		map.put(p4, 1);
		
		for(Person key: map.keySet()) {
			System.out.println(key + ": " + map.get(key));
		}
		
		Set<Person> set = new LinkedHashSet<Person>();
		
		set.add(p1);
		set.add(p2);
		set.add(p3);
		set.add(p4);
		
		System.out.println(set);
	}

}

{ID is: 0; name is: Bob}: 1
{ID is: 1; name is: Sue}: 1
{ID is: 2; name is: Mike}: 3
[{ID is: 0; name is: Bob}, {ID is: 1; name is: Sue}, {ID is: 2; name is: Mike}]

Learn to program Java Swing with my complete video course – desktop programming and applets. Includes 7 free videos. Click here for details.

All pages on this site are copyright © 2013 John W. Purcell

3 Responses to Using Custom Objects in Sets and as Map Keys: Java Collections Framework Video Tutorial, Part 6

  1. Der Flatulator says:

    Looking forward to the natural ordering tutorial. Will you be covering natural ordering of String?

    • Squiffy says:

      Well I’ll create a tutorial about sorting Lists in the next day or two hopefully, which will include how to sort strings. Then in the following tutorial I’ll look at defining a natural order for a class. Hopefully that will cover what you need, but let me know if you have anything specific in mind. Strings have a natural order of alphabetical order, but you could sort them in a different order using the technique I’ll cover in the next tutorial.

  2. Shaurabh says:

    Custom objects as key in map or set : the thing must be taken care is that the class should be immutable/atleast the fields used in equals() should be final(no setters).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Java, Java Collections Framework | Tagged , , , , , |