是否有类似于ArrayList的Java类可以执行此操作?

use*_*585 4 java arrays arraylist

我有时在编程时遇到这个问题.

想象一下,我有一个包含两列的数据表.第一列有字符串,第二列有整数.

我希望能够将表的每一行存储到动态数组中.因此,数组的每个元素都需要包含一个字符串和一个整数.

以前,我通过将表的每一列拆分为两个单独的ArrayLists来实现这一点,然后当我想添加一行时,我会在每个ArrayList上调用add()方法一次.要删除,我会在同一索引的每个ArrayList上调用remove(index)方法一次.

但是不是有更好的方法吗?我知道有类似HashMap的类,但它们不允许重复键.我正在寻找允许重复输入的东西.

我知道可以做这样的事情:

ArrayList<Object[]> myArray = new ArrayList<Object[]>();
myArray.add(new Object[]{"string", 123});
Run Code Online (Sandbox Code Playgroud)

每次我从数组中获取一个元素时,我真的不想要转换为String和Integer但是这可能是没有创建自己的唯一方法吗?这看起来更让我困惑,我更喜欢使用两个ArrayLists.

那么有没有像ArrayList这样的Java对象,它会像这样工作:

ArrayList<String, Integer> myArray = new ArrayList<String, Integer>();
myArray.add("string", 123);
Run Code Online (Sandbox Code Playgroud)

Ser*_*nko 10

只需创建简单的POJO类来保存行数据.不要忘了equals,并hashCode和喜欢一成不变的解决方案(没有制定者):

public class Pair {
    private String key;
    private Integer value;

    public Pair(String key, Integer value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public Integer getValue() {
        return value;
    }

    // autogenerated

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Pair)) return false;

        Pair pair = (Pair) o;

        if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
        if (value != null ? !value.equals(pair.value) : pair.value != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = key != null ? key.hashCode() : 0;
        result = 31 * result + (value != null ? value.hashCode() : 0);
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

    List<Pair> list = new ArrayList<Pair>();
    list.add(new Pair("string", 123));
Run Code Online (Sandbox Code Playgroud)

注意:在其他语言中有一些内置解决方案,如Scala中的case-classes和tuples.