简体   繁体   English

LinkedHashMap在所有键中都包含相同的值

[英]LinkedHashMap contains same Value in all Key

Im new in using LinkedHashMap, Im trying to store every instance of the array(bubble sort algorithm) in a LinkedHashMap by using the method .put , but when i try to retrieved the contents of the linkedhashmap, what i get is a bunch of copies of the final sorted array. 我是使用LinkedHashMap的新手,我试图使用.put方法将数组的每个实例(气泡排序算法)存储在LinkedHashMap中,但是当我尝试检索linkedhashmap的内容时,得到的是一堆副本最终排序数组的值。 How can i store all of the instance (occurence) of the array in the LinkedHashMap? 如何在LinkedHashMap中存储数组的所有实例(出现)? Please enlighten me 请赐教

This is my code: 这是我的代码:

private LinkedHashMap<String,double[]> sortBubbleAscend(double[] arrayKo2) {

    double temp = 0; 
    int count = 0;

    LinkedHashMap<String, double[]> map = new LinkedHashMap<String, double[]>();

    for(int i=0; i<arrayKo2.length; i++)
    {
        for(int j=0;j<arrayKo2.length-1;j++)
        {
            if(arrayKo2[j] > arrayKo2[j+1])
            {
                temp=arrayKo2[j];
                arrayKo2[j]=arrayKo2[j+1];
                arrayKo2[j+1]=temp;
            }
            count++;
            map.put("" + count, arrayKo2);       
        }       
    } 

    return map;
}

And this is the code that i use to monitor the value of LinkedHashMap 这是我用来监视LinkedHashMap的值的代码

     for (Entry<String, double[]> entry : map.entrySet()) 
    {   
        double[] value = entry.getValue();
        for(int p=0; p < value.length; p++)
        {
            Log.d("TEST", "Value: "+ value[p]);
        }
        Log.d("TEST", "----------------"); //printing line to separate each instance of the array   
    }

Thank You in advance 先感谢您

Use Arrays.copyOf(arrayKo2) instead of arrayKo2 when you put : 使用Arrays.copyOf(arrayKo2)而不是arrayKo2当你put

 map.put("" + count, Arrays.copyOf(arrayKo2, arrayKo2.length));

Otherwise every item of your Map will reference the same array, ie. 否则, Map每个项目都将引用相同的数组,即。 the one you are sorting. 您正在排序的那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM