Issue
I have an ArrrayList<String[][]>
with a couple of String[][]
in it. I want to extract out the 2D array that have same name as my String
value.
I have tried the method below and it end up with errors like:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Code in my fragment:
//String value
String value = getArguments().getString("choices");
//2D arrays
String[][] volume = {
{"(pascal)", "1"},
{"(kilopascal)", "0.001"},
{"(bar)", "0.00001"}}
String[][] length = {
{"(Meter)", "1"},
{"(Centimeter)", "100"},
{"(Kilometer)", "0.001"}}
String[][] weight = {
{"(kilometer per hour)", "1"},
{"(mile per hour)", "0.6213711922"},
{"(yard per hour)", "1093.6132983333"}}
//Array List
ArrayList<String[][]> stringList = new ArrayList<>();
stringList.add(weight);
stringList.add(length);
stringList.add(volume);
//Code for extracting the String[][] from arraylist
ArrayList<String> data = new ArrayList<>();
try {
for (int i = 0; i < stringList.size(); i++) {
if(stringList.get(i).toString().equals(value)){
for (int y = 0; y < stringList.get(i).length;) {
data.add(stringList.get(i)[y][0]);
y++;
}
}
}
}catch (Exception e){
Log.e(TAG, "onViewCreated: " + e );
}
Solution
This really seems to be a scenario where you could use HashMap<String, Double>
. It keeps the values in this form: key (of type String) -> value (of type Double)
. So you could completely remove your whole String[][]
complication.
Here is an example:
String value = getArguments().getString("choices");
//HashMaps
HashMap<String, Double> map = new HashMap<>();
map.put("(pascal)", 1d);
map.put("(kilopascal)", 0.001);
// and so on
// You should add everything here though and remove the need for an ArrayList. that just complicates things
map.get(value); // Returns the double value
I cannot understand exactly what you want to do and what is supposed to be in the value
variable. When you need to differentiate the map types (volume, length etc..) add yet another map that as key has String
and as value another HashMap<String, Double>
.
P.S: Try to log everything when you don't understand what is happening, some of your toString()
functions, return the reference of the object and not what you (most likely) expect.
Or even better, use a debugger.
Answered By - Renis1235