1

I have an ArrayList named play_viewCount: I am sorting this ArrryList and storing it in a new ArrayList.

Now I have sorted ArrayList: but what I want is before sorting what was the position of new items in ArrayList?

ArrayList<String> sort_play_viewCount = play_ViewCount; // here play_viewCount is ArrayList
ArrayList<Integer> position_array = new ArrayList<Integer>(); 
System.out.println("......................................... Play Count :"+sort_play_viewCount);
Collections.sort(sort_play_viewCount);
System.out.println(".........................................sort Play Count :"+sort_play_viewCount);

for(int j = 0; j<sort_play_viewCount.size(); j++){
    for(int k = 0; k<sort_play_viewCount.size(); k++){
        if(play_ViewCount.contains(sort_play_viewCount.get(j))){
            position_array.add(k);
        }
    }
}

System.out.println(" .................Position Array: "+position_array);

Does anyone know how to get the positions of the new items before sorting?

4

2 に答える 2

5

Try doing a little differently:

ArrayList<Integer> position_array = new ArrayList<Integer>(); 

position_array.addAll(play_viewCount);
Collections.sort(position_array);

Now position_array is sorted, and to get the previous positions you can just call play_viewCount.indexOf(value);

于 2012-05-22T14:49:47.533 に答える
2

You can put the elements of the ArrayList into a Map<String, Integer> (implemented by a HashMap<String, Integer>), where the key of an entry is String element from the ArrayList and the value is Integer representing the position.

Map<String, Integer> originalPositions = new HashMap<String, Integer>();

String item = ...
String position = ...
originalPositions.put(item, position);

// do something with the ArrayList, such as sorting
Collections.sort(arrayList);

String someItem = arrayList.get(i);
int originalPosition = originalPositions.get(someItem);

And by the way, this line from your code snippet doesn't do what you think it does:

ArrayList<String> sort_play_viewCount = play_ViewCount;

It doesn't create a new ArrayList with the same contents as the original one. Instead, it just creates a new reference to the original ArrayList. Both play_ViewCount and sort_play_viewCount refer to the very same object, in other words, any changes to one of the variables (such as sorting) also affect the other one.

To create a new copy (however, it is still shallow) of an ArrayList, use the following idiom:

ArrayList<Integer> original = ...
ArrayList<Integer> copy = new ArrayList<Integer>(original);
于 2012-05-22T14:52:38.250 に答える