0

I want to store several items, each with a specific set of attributes (Strings as well as Numbers), using Java. In Python, I would do this in a list: [item1 [attribute1, attribute2, attribute3 ...], item2 [attribute1, attribute2,..]].

The Lists, maps, Dictionaries in Java seem to be unuseful, as you can only store "at most one value", Arrays seem to be the most promising, but they con only contain values of one type - yet I need to store both Strings and Numbers. Is it possible to store data in Java in a similar way like in Python?

4

1 回答 1

0

您只需要定义自己的对象并存储该类型的列表:

public class MyObject {
    String att1;
    int att2;
    //...etc
    public MyObject(String _att1, int _att2) {
        att1 = _att1;
        att2 = _att2;
        //...etc
    }

}

然后从您的对象中创建一个列表:

List<MyOjbect> MyList = new ArrayList<MyObject>();
MyObject obj = new MyObject("att1", 2);
MyList.add(obj);

不像 Python 那样简洁,但您可以通过一些额外的代码获得相同的结果。

于 2013-04-30T16:53:18.087 回答