简体   繁体   English

Java关联数组

[英]Java associative-array

How can I create and fetch associative arrays in Java like I can in PHP? 如何在PHP中创建和获取Java中的关联数组?

For example: 例如:

$arr[0]['name'] = 'demo';
$arr[0]['fname'] = 'fdemo';
$arr[1]['name'] = 'test';
$arr[1]['fname'] = 'fname';

Java doesn't support associative arrays, however this could easily be achieved using a Map . Java不支持关联数组,但是使用Map可以轻松实现。 Eg, 例如,

Map<String, String> map = new HashMap<String, String>();
map.put("name", "demo");
map.put("fname", "fdemo");
// etc

map.get("name"); // returns "demo"

Even more accurate to your example (since you can replace String with any object that meet your needs) would be to declare: 对于您的示例更加准确(因为您可以使用满足您需求的任何对象替换String)将声明:

List<Map<String, String>> data = new ArrayList<>();
data.add(0, map);
data.get(0).get("name"); 

See the official documentation for more information 有关更多信息,请参阅官方文档

Java doesn't have associative arrays like PHP does. Java没有像PHP那样的关联数组。

There are various solutions for what you are doing, such as using a Map, but it depends on how you want to look up the information. 您正在使用各种解决方案,例如使用Map,但这取决于您希望如何查找信息。 You can easily write a class that holds all your information and store instances of them in an ArrayList . 您可以轻松编写一个包含所有信息的类,并将它们的实例存储在ArrayList

public class Foo{
    public String name, fname;

    public Foo(String name, String fname){
        this.name = name;
        this.fname = fname;
    }
}

And then... 然后...

List<Foo> foos = new ArrayList<Foo>();
foos.add(new Foo("demo","fdemo"));
foos.add(new Foo("test","fname"));

So you can access them like... 所以你可以像...一样访问它们

foos.get(0).name;
=> "demo"

You can accomplish this via Maps. 您可以通过地图完成此操作。 Something like 就像是

Map<String, String>[] arr = new HashMap<String, String>[2]();
arr[0].put("name", "demo");

But as you start using Java I am sure you will find that if you create a class/model that represents your data will be your best options. 但是当你开始使用Java时,我相信你会发现如果你创建一个代表你的数据的类/模型将是你最好的选择。 I would do 我会做

class Person{
String name;
String fname;
}
List<Person> people = new ArrayList<Person>();
Person p = new Person();
p.name = "demo";
p.fname = "fdemo";
people.add(p);

There is no such thing as associative array in Java. Java中没有关联数组这样的东西。 Its closest relative is a Map , which is strongly typed, however has less elegant syntax/API. 它最接近的是一个Map ,它是强类型的,但是它的语法/ API不太优雅。

This is the closest you can get based on your example: 根据您的示例,这是您可以获得的最接近的:

Map<Integer, Map<String, String>> arr = 
    org.apache.commons.collections.map.LazyMap.decorate(
         new HashMap(), new InstantiateFactory(HashMap.class));

//$arr[0]['name'] = 'demo';
arr.get(0).put("name", "demo");

System.out.println(arr.get(0).get("name"));
System.out.println(arr.get(1).get("name"));    //yields null

Look at the Map interface, and at the concrete class HashMap . 查看Map接口,以及具体的HashMap类。

To create a Map: 要创建地图:

Map<String, String> assoc = new HashMap<String, String>();

To add a key-value pair: 要添加键值对:

assoc.put("name", "demo");

To retrieve the value associated with a key: 要检索与键关联的值:

assoc.get("name")

And sure, you may create an array of Maps, as it seems to be what you want: 当然,你可以创建一个地图数组,因为它似乎是你想要的:

Map<String, String>[] assoc = ...

Well i also was in search of Associative array and found the List of maps as the best solution. 那么我也在搜索关联数组,并发现地图列表是最佳解决方案。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class testHashes {

public static void main(String args[]){
    Map<String,String> myMap1 = new HashMap<String, String>();

    List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();

    myMap1.put("URL", "Val0");
    myMap1.put("CRC", "Vla1");
    myMap1.put("SIZE", "Vla2");
    myMap1.put("PROGRESS", "Vla2");

    myMap.add(0,myMap1);
    myMap.add(1,myMap1);

    for (Map<String, String> map : myMap) {
        System.out.println(map.get("URL"));
    }

    //System.out.println(myMap);

}


}

Java相当于Perl的哈希值

HashMap<Integer, HashMap<String, String>> hash;

Java doesn't have associative arrays, the closest thing you can get is the Map interface Java没有关联数组,最接近的是Map接口

Here's a sample from that page. 这是该页面的示例。

import java.util.*;

public class Freq {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<String, Integer>();

        // Initialize frequency table from command line
        for (String a : args) {
            Integer freq = m.get(a);
            m.put(a, (freq == null) ? 1 : freq + 1);
        }

        System.out.println(m.size() + " distinct words:");
        System.out.println(m);
    }
}

If run with: 如果运行:

java Freq if it is to be it is up to me to delegate

You'll get: 你会得到:

8 distinct words:
{to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}

Use ArrayList < Map < String, String > > 使用ArrayList <Map <String,String >>

Here a code sample : 这里有一个代码示例:

ArrayList<Map<String, String>> products = new ArrayList<Map<String, String>>();
while (iterator.hasNext()) {
         Map<String, String> product = new HashMap<String, String>();
         Element currentProduct = iterator.next();
         product.put("id",currentProduct.get("id"));
         product.put("name" , currentProduct.get("name") );
         products.add(product );
}
System.out.println("products : " + products);

Output : 输出:

products : [{id=0001, name=prod1}, {id=0002, name=prod2}] 产品:[{id = 0001,name = prod1},{id = 0002,name = prod2}]

Associative arrays in Java like in PHP : Java中的关联数组,如PHP:

SlotMap hmap = new SlotHashMap();
String key = "k01";
String value = "123456";
// Add key value
hmap.put( key, value );

// check if key exists key value
if ( hmap.containsKey(key)) {
    //.....        
}

// loop over hmap
Set mapkeys =  hmap.keySet();
for ( Iterator iterator = mapkeys.iterator(); iterator.hasNext();) {
  String key = (String) iterator.next();
  String value = hmap.get(key);
}

More info, see Class SoftHashMap : https://shiro.apache.org/static/1.2.2/apidocs/org/apache/shiro/util/SoftHashMap.html 更多信息,请参阅类SoftHashMap: https ://shiro.apache.org/static/1.2.2/apidocs/org/apache/shiro/util/SoftHashMap.html

Object[][] data = {
{"mykey1", "myval1"},
{"mykey2", "myval2"},
{new Date(), new Integer(1)},
};

Yes, this require iteration for searchting value by key, but if you need all of them, this will be the best choice. 是的,这需要迭代按键搜索值,但如果你需要所有这些,这将是最好的选择。

In JDK 1.5 (http://tinyurl.com/3m2lxju) there is even a note: "NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class." 在JDK 1.5(http://tinyurl.com/3m2lxju)中,甚至还有一个注释:“注意:这个类已经过时了。新的实现应该实现Map接口,而不是扩展这个类。” Regards, N. 问候,N。

Thinking more about it, I would like to throw out tuples as a more general-purpose way of dealing with this problem. 考虑更多,我想抛出元组作为处理这个问题的更通用的方法。 While tuples are not native to Java, I use Javatuples to provide me the same functionality which would exist in other languages. 虽然元组不是Java的原生元素 ,但我使用Javatuples为我提供了与其他语言相同的功能。 An example of how to deal with the question asked is 如何处理问题的一个例子是

Map<Pair<Integer, String>, String> arr = new HashMap<Pair<Integer, String>, String>();
Pair p1 = new Pair(0, "name");
arr.put(p1, "demo");

I like this approach because it can be extended to triples and other higher ordered groupings with api provided classes and methods. 我喜欢这种方法,因为它可以通过api提供的类和方法扩展到三元组和其他更高阶的分组。

实际上Java确实支持关联数组,它们被称为字典!

Regarding the PHP comment 'No, PHP wouldn't like it'. 关于PHP评论'不,PHP不喜欢它'。 Actually, PHP would keep on chugging unless you set some very restrictive (for PHP) exception/error levels, (and maybe not even then). 实际上,除非你设置一些非常严格的限制(对于PHP)异常/错误级别(并且可能甚至不是这样),否则PHP将继续使用。

What WILL happen by default is that an access to a non existing variable/out of bounds array element 'unsets' your value that you're assigning to. 默认情况下会发生的是,访问非现有变量/越界数组元素会“取消”您指定的值。 NO, that is NOT null. 不,那不是空的。 PHP has a Perl/C lineage, from what I understand. 根据我的理解,PHP有一个Perl / C谱系。 So there are: unset and non existing variables, values which ARE set but are NULL, Boolean False values, then everything else that standard langauges have. 所以有:未设置和不存在的变量,ARE设置但是为NULL的值,布尔值为假值,然后是标准语言的所有其他值。 You have to test for those separately, OR choose the RIGHT evaluation built in function/syntax. 您必须单独测试这些,或者选择内置函数/语法的RIGHT评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM