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, ie. the one you are sorting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.