How to hashMap an array in Java?

java hashmap array to double array

  • I declared LinkedHashMap<String, float[]> and now I want to convert float[] values into double[][]. I am using following code. LinkedHashMap<String, float[]> fData; double data[][] = null; Iterator<String> iter = fData.keySet().iterator(); int i = 0; while (iter.hasNext()) { faName = iter.next(); tValue = fData.get(faName); //data = new double[fData.size()][tValue.length]; for (int j = 0; j < tValue.length; j++) { data[i][j] = tValue[j]; } i++; } When I try to print data System.out.println(Arrays.deepToString(data)); it doesn't show the data :( I tried to debug my code and i figured out that I have to initialize data outside the while loop but then I don't know the array dimensions :( How to solve it? Thanks

  • Answer:

    Try this: LinkedHashMap<String, float[]> fData; double data[][] = new double[fData.size()][]; int i = 0; for( String key in fData.keys() ) { float[] tValue = fData.get(key); data[i] = new double[ tValue.length ]; for (int j = 0; j < tValue.length; j++) { data[i][j] = tValue[j]; } i++; }

Tweety at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

I think the problem is that there are two steps here that you are trying to conflate into one. First, you want to create an array of arrays large enough to hold all of the individual arrays: double[][] data = new double[fData.size()][]; Next, you'll want to iterate over all the entries, building an array large enough to hold the value: double[][] data = new double[fData.size()][]; int index = 0; for (float[] entry: fData.values()) { /* ... */ ++index; } At each of these loop iterations, you'll want to allocate an array to hold all of the floats: double[][] data = new double[fData.size()][]; int index = 0; for (float[] entry: fData.values()) { data[index] = new double[entry.length]; /* ... */ ++index; } And finally, you'll want to copy the data in: double[][] data = new double[fData.size()][]; int index = 0; for (float[] entry: fData.values()) { data[index] = new double[entry.length]; for (int i = 0; i < entry.length; ++i) data[index][i] = entry[i]; ++index; } And you should be golden!

templatetypedef

You need: double data[][] = new double[fData.size()][]; Then later in the loop, you need: data[i] = new double[tValue.length];

Bert F

double data[][] = new data[fData.size()][]; data[i] = new double[tValue.length];

jtahlborn

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.