gpt4 book ai didi

java - 将 PHP 数组数据结构移植到 Java 中

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:49 24 4
gpt4 key购买 nike

我正在 PHP 中使用此数据结构

Array
(
[leigh@bla] => Array
(
[chat1] => Array
(
[0] => Array
(
[0] => 0
[1] => hi
[2] => 123213312
)

)

[chat2] => Array
(
[0] => Array
(
[0] => 0
[1] => whatever?
[2] => 123213312
)

[1] => Array
(
[0] => 1
[1] => ok
[2] => 23123213
)

)

)

[nelson@bla] => Array
(
[chat1] => Array
(
[0] => Array
(
[0] => 1
[1] => hello
[2] => 1232132123
)

)

)

)

这是 PHP 代码:

<?php
$arrTemp['leigh@bla']['chat1'][] = array(0, 'hi', '123213312');
$arrTemp['leigh@bla']['chat2'][] = array(0, 'whatever?', '123213312');
$arrTemp['leigh@bla']['chat2'][] = array(1, 'ok', '23123213');

$arrTemp['nelson@bla'] = array('chat1'=>array(array(1, 'hello', '1232132123')));

echo '<pre>';

print_r($arrTemp);

我正在尝试用 Java 存储这个结构。但是很难找到合适的类型,我尝试过 ArrayList> 等。在 Java 中存储此结构的最佳方法是什么?

最佳答案

外部结构似乎是一个关联数组(键是“leigh”),因此对于该级别,您需要一个(Hash)Map(java中没有关联数组,Map是等效的)。

里面似乎是一个列表列表,里面有一些结构,其中包含 3 个原子值(我们称它们为 a、b 和 c),看起来像 IntegerStringInteger

这 3 个值的简单容器如下所示:

class InnerStructure {
Integer a, c;
String b;
}

并代表您的结构:

Map<String, List<List<InnerStructure>>> wholeStructure;

请注意,MapList 只是接口(interface),它们的实现是 HashMapLinkedListArrayList

模仿您的 php 代码来填充此结构:

Map<String, List<List<InnerStructure>>> wholeStructure = new HashMap<String, List<List<InnerStructure>>>();
List<List<InnerStructure>> outerList = new ArrayList<List<InnerStructure>>();
List<InnerStructure> innerList = new ArrayList<InnerStructure>();

InnerStructure innerData = new InnerStructure();
innerData.a = 1;
innerData.b = "hello";
innerData.c = 1232132123;

innerList.add(innerData);
outerList.add(innerList);

wholeStructure.put("leigh", outerList);

当然,我强烈建议您不要简单地使用无名列表,而是查找描述此层次结构实际用途的名称或术语。然后,您为这些创建类,并将列表聚合到这些类中,这使其更具可读性、类型安全并且检查起来更轻松。

关于java - 将 PHP 数组数据结构移植到 Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17728062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com