문제

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. How can i store all of the instance (occurence) of the array in the 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

     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:

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

Otherwise every item of your Map will reference the same array, i.e.. the one you are sorting.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top