How to Eliminate Duplicate Keys from Hashtable in Java


Here this example demonstrates how to eliminate duplicate keys (user-defined objects) with hashCode and equals methods in custom classes.In the storage process, the system will first look for whether there is the same hashcode value in the collection. If there is no same value, it will store it. If there is, it will use equals to judge,here is a small example.

Source Code

– Student

package com.beginner.examples;

public class Student {

	private String stuID;

	private String name;

	private int age;

	public Student(String stuID, String name, int age) {
		this.stuID = stuID;
		this.name = name;
		this.age = age;
	}

	public String getStuID() {
		return stuID;
	}

	public void setStuID(String stuID) {
		this.stuID = stuID;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public boolean equals(Object o) {
		if (!(o instanceof Student)) {
			return false;
		}
		Student stu = (Student) o;

		// Students with the same student number and name are regarded as the same
		// student
		return stu == null ? false : this.stuID.equals(stu.stuID) && this.name.equals(stu.name);
	}

	@Override
	public int hashCode() {

		return this.name.hashCode();

	}
	
	@Override
	public String toString() {
		return name +","+stuID + "," + age;
	}

}

– HashtableTest

package com.beginner.examples;

import java.util.Hashtable;
import java.util.Map;
import java.util.Set;


public class HashtableTest {

	public static void main(String[] args) {
		
		Hashtable stuTable = new Hashtable();
		
		//Add some student objects and store Tom and Jerry repeatedly
		stuTable.put(new Student("Tom","1001",20), "Tom");
		stuTable.put(new Student("Jerry","1002",21), "Jerry");
		stuTable.put(new Student("John","1003",20), "John");
		stuTable.put(new Student("Tom","1001",20), "Tom");
		stuTable.put(new Student("Jerry","1002",20), "Jerry");
		
		
		Set<Map.Entry> entries = stuTable.entrySet();
		
		for(Map.Entry entry : entries) {
			
			Student student = entry.getKey();
			String name = entry.getValue();
			
			System.out.println(student+"----------"+name);
		}
		
	}
	
}

Output:

1003,John,20----------John
1002,Jerry,21----------Jerry
1001,Tom,20----------Tom

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments