Java 是否支持关联数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4993366/
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-10-30 08:58:35  来源:igfitidea点击:

Does Java support associative arrays?

javaarrays

提问by Fugogugo

I'm wondering if arrays in Java could do something like this:

我想知道 Java 中的数组是否可以做这样的事情:

int[] a = new int[10];
a["index0"] = 100;
a["index1"] = 100;

I know I've seen similar features in other languages, but I'm not really familiar with any specifics... Just that there are ways to associate values with string constants rather than mere numeric indexes. Is there a way to achieve such a thing in Java?

我知道我在其他语言中看到过类似的功能,但我对任何细节都不太熟悉......只是有一些方法可以将值与字符串常量相关联,而不仅仅是数字索引。有没有办法在Java中实现这样的事情?

采纳答案by POSIX_ME_HARDER

I don't know a thing about C++, but you are probably looking for a Class implementing the Map interface.

我对 C++ 一无所知,但您可能正在寻找实现Map 接口的类。

回答by Matt Ball

You can't do this with a Java array. It sounds like you want to use a java.util.Map.

你不能用 Java 数组来做到这一点。听起来您想使用java.util.Map.

Map<String, Integer> a = new HashMap<String, Integer>();

// put values into the map
a.put("index0", 100); // autoboxed from int -> Integer
a.put("index1", Integer.valueOf(200));

// retrieve values from the map
int index0 = a.get("index0"); // 100
int index1 = a.get("index1"); // 200

回答by king_nak

What you need is java.util.Map<Key, Value>interface and its implementations (e.g. HashMap) with Stringas key

您需要的是java.util.Map<Key, Value>接口及其实现(例如HashMap) with Stringas key

回答by Tom Anderson

To store things with string keys, you need a Map. You can't use square brackets on a Map. You can do this in C++ because it supports operator overloading, but Java doesn't.

要使用字符串键存储内容,您需要一个 Map。您不能在 Map 上使用方括号。您可以在 C++ 中执行此操作,因为它支持运算符重载,但 Java 不支持。

There is a proposal to add this syntax for maps, but it will be added for Java 8 at the earliest.

有人提议为地图添加此语法,但最早将在Java 8 中添加。

回答by lahiru madhumal

java does not have associative arrays yet. But instead you can use a hash map as an alternative.

java 还没有关联数组。但是,您可以使用哈希映射作为替代方案。

回答by lahiru madhumal

Are you looking for the HashMap<k,v>()class? See the javadocshere.

你在找HashMap<k,v>()班级吗?请参阅此处的javadoc

Roughly speaking, usage would be:

粗略地说,用法是:

HashMap<String, int> a = new HashMap<String,int>();
a.put("index0", 100);

etc.

等等。