三维列表或地图

use*_*330 12 java arrays dictionary list

我需要一些像3维(如列表或地图)的东西,我在循环中填充2个字符串和一个整数.但是,遗憾的是我不知道使用哪种数据结构以及如何使用.

// something like a 3-dimensional myData
for (int i = 0; i < 10; i++) {
    myData.add("abc", "def", 123);
}
Run Code Online (Sandbox Code Playgroud)

duf*_*ymo 19

创建一个将三者封装在一起的对象,并将它们添加到数组或List中:

public class Foo {
    private String s1;
    private String s2; 
    private int v3;
    // ctors, getters, etc.
}

List<Foo> foos = new ArrayList<Foo>();
for (int i = 0; i < 10; ++i) {
    foos.add(new Foo("abc", "def", 123);
}
Run Code Online (Sandbox Code Playgroud)

如果要插入数据库,请编写DAO类:

public interface FooDao {
    void save(Foo foo);    
}
Run Code Online (Sandbox Code Playgroud)

根据需要使用JDBC实现.


Tom*_*art 12

Google的Guava代码如下所示:

import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;

Table<String, String, Integer> table = HashBasedTable.create();

for (int i = 0; i < 10; i++) {
    table.put("abc", "def", i);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将在HashMap中构造一个HashMap,其构造函数如下所示:

Table<String, String, Integer> table = Tables.newCustomTable(
        Maps.<String, Map<String, Integer>>newHashMap(),
        new Supplier<Map<String, Integer>>() {
    @Override
    public Map<String, Integer> get() {
        return Maps.newHashMap();
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您想覆盖底层结构,可以轻松更改它.


UmN*_*obe 5

只需创建一个类

 class Data{
  String first;
  String second;
  int number;
 }
Run Code Online (Sandbox Code Playgroud)