[英]how do I add elements/data on my two dimensional ArrayList?
I'm trying to make an inventory program, and i think it would be nice to make use of two dimensional ArrayList, 我正在尝试制作库存程序,并且我认为使用二维ArrayList会很好,
lets say i have an item code String
" 001 " which will be stored on the first array index [0] and store the other datas on the other array since it's a two dimensional array, which contains the item name, description, and price also a String
. 假设我有一个商品代码
String
“ 001 ”,它将存储在第一个数组索引[0]上,并将其他数据存储在另一个数组中,因为它是一个二维数组,其中包含商品名称,说明和价格一个String
。
so its gonna look something like this, 所以它看起来像这样,
http://i.stack.imgur.com/YuQvJ.png http://i.stack.imgur.com/YuQvJ.png
now, how can I store all the data's and output all the the datas? 现在, 如何存储所有数据并输出所有数据?
thanks! 谢谢!
You don't want a 2D array, or an ArrayList
of ArrayList
s. 您不需要2D数组或
ArrayList
的ArrayList
。 Not all of your fields are of the same type. 并非您所有的字段都属于同一类型。 I think you should make a class
Item
that has fields name
, description
and price
, then make an ArrayList
or an array of Item
s. 我认为您应该制作一个具有字段
name
, description
和price
Item
类,然后制作一个ArrayList
或Item
的数组。
What you really want is a Map
( http://docs.oracle.com/javase/7/docs/api/java/util/Map.html ). 您真正想要的是一个
Map
( http://docs.oracle.com/javase/7/docs/api/java/util/Map.html )。
A List
is meant to hold items, but not to index them or make them easily searchable. List
用于保存项目,但不对它们建立索引或使它们易于搜索。 A Map
, though, does just that. 不过,
Map
就是这样做的。 Each item that gets put into a map has a key that uniquely identifies it. 放入地图中的每个商品都有一个唯一标识它的钥匙。 Let's pretend that your product is named
Product
. 假设您的产品名为
Product
。 You could have a map like this: 您可能会有这样的地图:
Map<Integer, Product> map = new HashMap<Integer, Product>();
Product p = new Product("some name", "some desc");
// Put the item into the map
map.put(1, p);
// Get item back
Product sameAsP = map.get(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.