Java:创建一个 2D ArrayList 来存储整数和字符串?

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

Java: Creating a 2D ArrayList to store an integer and string?

javaarraylistmultidimensional-array

提问by Cryssie

I need to store 2 arrays of values that are connected to each other. The arrays consists of a set of strings and a set of integer/double values. The size of the data are not fixed.

我需要存储 2 个相互连接的值数组。数组由一组字符串和一组整数/双精度值组成。数据的大小不是固定的。

An example:

一个例子:

Data 1: AA, 13    
Data 2: BB, 6    
Data 3: GG, 2

I am trying to look at 2D Arrays. Is there a better way to store the values? There's a possibilities that I might need multidimensional arrays to store the values as well. Can anyone point me in the right direction or show me a way to create the 2D arrays and how to add/retrieve the elements?

我正在尝试查看二维数组。有没有更好的方法来存储值?有可能我也需要多维数组来存储值。谁能指出我正确的方向或向我展示一种创建二维数组的方法以及如何添加/检索元素?

回答by Makoto

It would be farbetter to use a Map. Maps have key-value pairs, so you could naturally store Strings and Integers in this manner.

这将是迄今为止最好使用Map。映射具有键值对,因此您可以自然地以这种方式存储字符串和整数。

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

回答by TaherT

You can also use like this there are two ways if you want only ArrayList as a datastructure create a class like this :

如果您只想将 ArrayList 作为数据结构创建一个这样的类,您也可以像这样使用有两种方法:

    public Class Data{
    private String myString;
    private Integer myInteger;
    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }

    public Integer getMyInteger() {
        return myInteger;
    }

    public void setMyInteger(Integer myInteger) {
        this.myInteger = myInteger;
    }
}
List<Data> list = new ArrayList<Data>();

or else you can use like this

List<Object[]> list = new ArrayList<Object[]>();