简体   繁体   中英

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,

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 .

so its gonna look something like this,

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. 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.

What you really want is a 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. A Map , though, does just that. Each item that gets put into a map has a key that uniquely identifies it. Let's pretend that your product is named 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM