开发者

Convert a float[] to a double[] inside a HashMap

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 t开发者_开发问答o 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


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!


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++;
}


You need:

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

Then later in the loop, you need:

data[i] = new double[tValue.length];


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

data[i] = new double[tValue.length];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜