如何在 Java 中创建哈希表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:20:45  来源:igfitidea点击:

How do I create a hash table in Java?

javahashhashmap

提问by akdom

What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this?

在 Java 中创建哈希表(或关联数组...)的最直接方法是什么?我的 google-fu 出现了几个例子,但是有没有标准的方法来做到这一点?

And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?

有没有一种方法可以用键-> 值对列表填充表,而无需为每一对单独调用对象上的 add 方法?

采纳答案by Edmund Tay

Map map = new HashMap();
Hashtable ht = new Hashtable();

Both classes can be found from the java.util package. The difference between the 2 is explained in the following jGuru FAQ entry.

这两个类都可以从 java.util 包中找到。下面的jGuru FAQ 条目解释了两者之间的区别。

回答by John

import java.util.HashMap;

Map map = new HashMap();

回答by SCdF

What Edmundsaid.

什么埃德蒙说。

As for not calling .add all the time, no, not idiomatically. There would be various hacks (storing it in an array and then looping) that you could do if you really wanted to, but I wouldn't recommend it.

至于不一直调用 .add ,不,不是惯用的。如果您真的愿意,您可以使用各种技巧(将其存储在数组中然后循环),但我不会推荐它。

回答by Cem Catikkas

Also don't forget that both Map and Hashtable are generic in Java 5 and up (as in any other class in the Collections framework).

另外不要忘记 Map 和 Hashtable 在 Java 5 及更高版本中都是通用的(就像在集合框架中的任何其他类中一样)。

Map<String, Integer> numbers = new HashMap<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);

Integer one = numbers.get("one");
Assert.assertEquals(1, one);

回答by Mocky

And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?

有没有一种方法可以用键-> 值对列表填充表,而无需为每一对单独调用对象上的 add 方法?

One problem with your question is that you don't mention what what form your data is in to begin with. If your list of pairs happened to be a list of Map.Entry objects it would be pretty easy.

你的问题的一个问题是你没有提到你的数据是从什么形式开始的。如果您的配对列表恰好是 Map.Entry 对象列表,那将非常容易。

Just to throw this out, there is a (much maligned) class named java.util.Properties that is an extension of Hashtable. It expects only String keys and values and lets you load and store the data using files or streams. The format of the file it reads and writes is as follows:

为了抛出这个问题,有一个名为 java.util.Properties 的(备受诟病的)类,它是 Hashtable 的扩展。它只需要字符串键和值,并允许您使用文件或流加载和存储数据。它读写的文件格式如下:

key1=value1
key2=value2

I don't know if this is what you're looking for, but there are situations where this can be useful.

我不知道这是否是您要查找的内容,但在某些情况下这会很有用。

回答by izb

You can use double-braces to set up the data. You still call add, or put, but it's less ugly:

您可以使用双大括号来设置数据。你仍然调用 add 或 put,但它不那么难看:

private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{
    put("foo",      1);
    put("bar",      256);
    put("data",     3);
    put("moredata", 27);
    put("hello",    32);
    put("world",    65536);
 }};

回答by hedrick

It is important to note that Java's hash function is less than optimal. If you want less collisions and almost complete elimination of re-hashing at ~50% capacity, I'd use a Buz Hash algorithm Buz Hash

需要注意的是,Java 的哈希函数不是最优的。如果您想要更少的冲突并几乎完全消除大约 50% 容量的重新散列,我会使用 Buz Hash 算法Buz Hash

The reason Java's hashing algorithm is weak is most evident in how it hashes Strings.

Java 的散列算法很弱的原因最明显的是它如何散列字符串。

"a".hash()give you the ASCII representation of "a"- 97, so "b"would be 98. The whole point of hashing is to assign an arbitrary and "as random as possible" number.

"a".hash()给你的ASCII表示"a"- 97,所以"b"98。散列的全部意义在于分配一个任意且“尽可能随机”的数字。

If you need a quick and dirty hash table, by all means, use java.util. If you are looking for something robust that is more scalable, I'd look into implementing your own.

如果您需要一个快速而肮脏的哈希表,请务必使用java.util. 如果您正在寻找更具可扩展性的强大功能,我会考虑实现您自己的。

回答by Juraj Valku?ák

Hashtable<Object, Double> hashTable = new Hashtable<>();

put values...

把值...

get max

得到最大值

Optional<Double> optionalMax = hashTable.values().stream().max(Comparator.naturalOrder());

if (optionalMax.isPresent())
 System.out.println(optionalMax.get());