哈希表比较器问题

发布于 2024-08-23 23:34:22 字数 1379 浏览 4 评论 0原文

大家好,我从来没有写过比较器 b4,我遇到了一个真正的问题。我创建了一个哈希表。

Hashtable <String, Objects> ht;

有人可以展示如何为哈希表编写比较器吗?我见过的例子超越了等于和一切,但我根本不知道。下面的代码不是我的,而是我发现的一个例子,哈希表中的关键部分意味着我不能像这样做,我猜。

 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));
        }
    }

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));
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酷到爆炸 2024-08-30 23:34:23

比较器会告诉您两个项目中哪一个更大。如果这对您的哈希表有意义,那么只有您可以说出其含义是什么。以这种方式比较两个哈希表是非常不寻常的。

A Comparator will tell you which of two items is larger. If this has meaning for your HashTable, only you can say what the meaning is. It would be very unusual to want to compare two HashTables in this way.

执手闯天涯 2024-08-30 23:34:23

那不是 Comparator 类。这是一个实现 Comparable 的 Name 类。

Hashtable 和 Hashmap 不使用 Comparator 或 Comparable。如果您想要排序键,请使用 TreeMap。

That's not a Comparator class. That's a Name class that implements Comparable.

Hashtable and Hashmap don't use either Comparator or Comparable. If you want sorted keys use a TreeMap.

扮仙女 2024-08-30 23:34:23

比较器用于对列表进行排序。 Hashtable(注意大小写)不按其元素排序。您可以通过迭代表的键来对表进行排序(我猜想是在您想要对其键进行排序的情况下)并将它们放入 List 中。接下来要做的就是对 List 进行排序并迭代 List,并使用 Hashtable 中的 get code> 获取其关联值。

下面是一个示例(使用 HashMap,因为它与 Java 集合的其余部分集成得更好。HashMap 本质上与 Hashtable 相同。 ):

public static void main(String... arg) {
    HashMap<String, Object> x = new HashMap<String, Object>();
    x.put("second", " ordered!");
    x.put("first", "Correctly");

    LinkedList<String> keys = new LinkedList<String>();
    for(final String f : x.keySet()) {
        keys.add(f);
    }
    Collections.sort(keys, new Comparator<String>() {
        public int compare(String first, String second) {
            // return -1 is "first <  second"
            // return 1  is "first >  second"
            // return 0  is "first == second"
            return first.compareTo(second);
        }
    });

    for(final String f : keys) {
        System.out.print(x.get(f));
    }
    System.out.println();
}

列表keys的顺序由匿名Comparator类排序。它将按字母顺序排序,这是字符串的默认值。您可以使用自己的密钥对象,就像您提到的那样。如果您没有在此关键对象中实现Comparator,那么您可以提供,如上面的示例所示。否则,您可以通过调用以下命令来使用默认的 Comparator:

Collections.sort(keys);

这将使用 Comparator 的类实现。如果它没有实现Comparator,那么它将抛出异常(因为它将转换为Comparator

Comparators are used to sort a list. A Hashtable (note the case) is not ordered by its elements. You can order a table by iterating over its keys (in the case you'd want to order on its keys, I presume) and put them in a List. The next thing to do is to sort the List and iterate over the List, and use a get out of the Hashtable to get its associated value.

Here is an example (using HashMap, since it's more integrated with the rest of the Java Collections. A HashMap is essentially the same as Hashtable.):

public static void main(String... arg) {
    HashMap<String, Object> x = new HashMap<String, Object>();
    x.put("second", " ordered!");
    x.put("first", "Correctly");

    LinkedList<String> keys = new LinkedList<String>();
    for(final String f : x.keySet()) {
        keys.add(f);
    }
    Collections.sort(keys, new Comparator<String>() {
        public int compare(String first, String second) {
            // return -1 is "first <  second"
            // return 1  is "first >  second"
            // return 0  is "first == second"
            return first.compareTo(second);
        }
    });

    for(final String f : keys) {
        System.out.print(x.get(f));
    }
    System.out.println();
}

The order of the list keys is sorted by the anonymous Comparator class. It will sort alphabetically, as is the default for Strings. You can use your own key object, like you mentioned. If you don't implement Comparator in this key object, then you can supply, as in the above example. Else you can use the default Comparator by calling:

Collections.sort(keys);

Which will use the classes implementation of Comparator. If it does not implement Comparator, then it will throw an exception (since it will cast to a Comparator)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文