0

I have this code:

public class Item{
String name, color;
int weight, volume, cost;

public Item(String name, int weight, int volume, int cost, String color){
    this.name= name;
    this.weight = weight;
    this.volume = volume;
    this.cost = cost;
    this.color = color;
}

I used this to create an ArrayList of items by loading in a csv file with the data. I have items in the array such as Apple, Pear, Noodles, etc. Currently to look at the items I have to call itemList.get(2). I'd love to be able to call itemList.APPLE or some variation so I don't have to always know that the index number associated with the item. Is there a way to do this? It seems like it would be an enum trick.

.

Next I have a class that is similar but I want to create an object x with:

Item x = new Item(200, weight);

x.toString() ............... outputs: weight= 200, volume= 0, cost= 0, value= 0, base= 0, height= 0

from this code:

public class Item{
int weight, volume, cost, value,
base, height;

public Item(int x, String variable) {
    //some code 
}

in the code I would start by setting all the variables equal to 0, but then I need to use the string value to select which variable to add x to. How would I do this? I could use a big if, if else, if else statement adding x to the respective variable if the string.equals("__"), but I simplified the variables; there are actually about 30 of them. Do I just have to make a really long if statement or is there a better way?

Community
  • 1
  • 1
user12092
  • 39
  • 5

2 Answers2

0

First, depending on the list abstraction you're using, you can specify where you're putting the values. If instead you want to retrieve a particular object at any time, look into a Map instead:

Map<String, Item> itemMap = new HashMap<>();
itemMap.put("apples", new Item("Apple", 1, 1, 1, "Red"));
itemMap.get("apples");  // gives you the item you placed in as an Apple

Of course, you'd want to override equals() and hashCode() before doing that. Furthermore, you won't be allowed to enter duplicate values to the mapping.

Next, the second could be done with reflection, but why not just use conventional setters and getters?

Item item = new Item(); // or whichever constructor you choose
item.setWeight(200); // sets weight to 200
System.out.println(item); // will print item as you wish
Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230
0

Replace the 30 variables with a Map, mapping each name to its value.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75