Hashtable comparator problem

Posted by user288245 on Stack Overflow See other posts from Stack Overflow or by user288245
Published on 2010-03-07T16:43:43Z Indexed on 2010/03/08 0:30 UTC
Read the original article Hit count: 628

Filed under:
|
|
|

Hi guys i've never written a comparator b4 and im having a real problem. I've created a hashtable.

Hashtable <String, Objects> ht;

Could someone show how you'd write a comparator for a Hashtable? the examples i've seen overide equals and everything but i simply dont have a clue. The code below is not mine but an example i found, the key thing in hashtables means i cant do it like this i guess.

 public class Comparator implements Comparable<Name> {
        private final String firstName, lastName;

        public void Name(String firstName, String lastName) {
            if (firstName == null || lastName == null)
                throw new NullPointerException();
        this.firstName = firstName;
            this.lastName = lastName;
        }

        public String firstName() { return firstName; }
        public String lastName()  { return lastName;  }

        public boolean equals(Object o) {
            if (!(o instanceof Name))
                return false;
            Name n = (Name)o;
            return n.firstName.equals(firstName) &&
                   n.lastName.equals(lastName);
        }

        public int hashCode() {
            return 31*firstName.hashCode() + lastName.hashCode();
        }

        public String toString() {
        return firstName + " " + lastName;
        }

        public int compareTo(Name n) {
            int lastCmp = lastName.compareTo(n.lastName);
            return (lastCmp != 0 ? lastCmp :
                    firstName.compareTo(n.firstName));
        }
    }

© Stack Overflow or respective owner

Related posts about hashtable

Related posts about comparator