One problem that I am facing in my code is that I have a long list of strings that map to different integers. For example, "Apple" maps to 4, "Bat" maps to 7, etc. Is there any ways to create an Array List such that a string is used as the input search element rather than a traditional number? Ie. Array["Apple"] instead of Array[4]
4 Answers
Use an associative data structure for this.
Map<String, Integer> items = new HashMap<>();
items.put("Apple", 4);
items.put("Bat", 7);
items.get("Apple");
items.get("Bat");
1 Comment
John C.
Thank you for the quick, detailed response!
You will need two data structures for this problem: a Map to associate item names with indices and a List to store the items (e.g. an ArrayList). For example (untested):
// Store the items and a mapping of their indices by name.
List<String> items = new ArrayList<String>();
Map<String, Integer> itemIndices = new HashMap<String, Integer>();
// Add the item to both data structures.
itemIndices.put("Apple", 4);
items.add("Apple", 4);
// Now you can fetch them by name.
items.get(itemIndices.get("Apple")); // => "Apple"
Of course, you can use a Map<String,Integer> directly, with no need for the List...
enumtype; they can have values, and their names are available as strings, and you can look them up by their string name.