I've got a HashMap<Object, String[]> I just want to grab the 0 index position from the String[]. How do I do that?
Can I just do this? mMap.get(position)[0]?
I've got a HashMap<Object, String[]> I just want to grab the 0 index position from the String[]. How do I do that?
Can I just do this? mMap.get(position)[0]?
Yes, you can do what you've indicated, provided position is a key in the map.
position is a key.HashMap doesn't have a 0index and it doesn't have a String[]
You cannot do what you ask because it doesn't make sense.
Can I just do this? mMap.get(position)[0]?
You can. Have you tried this to see if it works? Note: it will fail if map.get() returns null
A map is not an array. It's a dictionary of keys that map to items. So there is no ordered index in the Map part, there's a lookup key. This means that a Map has no "next" item.
In the event that you stored a String[] in the map, then you could get the first element of the String array like so:
String first = ((String[])mMap.get(lookupKey))[0];
Since you are using generics, your compiler will make the casting unnecessary, simplifying the answer to
String first = mMap.get(lookupKey)[0];
Note that this is not using the position to access the item stored in the Map, it's using the lookup key. In addition, there is a casting of the returned Object into a String[] (because we stored a String[] in the map earlier), and then there is a dereferncing of the first ('0') element.
Here is a little demo program that does what you're asking.
import java.util.Map;
import java.util.HashMap;
public class FirstElementInHashMap {
public static void main(String[] args) {
Map<Object,String[]> mMap = new HashMap<Object,String[]>();
mMap.put("myKeyA", new String[] { "myValue1", "myValue2", "myValue3" });
mMap.put("myKeyB", new String[] { "myValue4", "myValue5", "myValue6" });
mMap.put("myKeyC", new String[] { "myValue7", "myValue8", "myValue9" });
Object position = "myKeyB";
String[] strings = mMap.get(position);
// make sure position exists in the Map and contains a non-empty array
// so we don't throw an NullPointerException
String firstStringInArray = null;
if (strings != null && strings.length > 0) {
firstStringInArray = strings[0];
}
System.out.println(firstStringInArray);
}
}
The output of the above program is:
myValue4