-5

I have ArrayList which contains a value and index, how can i sort the value without sorting the index?

example:

 ArrayList<Integer> arr = new ArrayList<Integer>();
 arr.add(1,100);
 arr.add(2,50);
 arr.add(3,10);

the result will be {(3,10),(2,50),(1,100)} thanks :D

Roman C
  • 49,761
  • 33
  • 66
  • 176
bohr
  • 631
  • 2
  • 9
  • 29

2 Answers2

0

What you're asking doesn't make sense because an element's index is directly tied to how it is sorted. You should use a Map or something similar.

Embattled Swag
  • 1,479
  • 12
  • 23
  • Actually i confused what structure i must use. i want to classified an image using knn and euclidean distance. the distance is the difference between RGB of each image. So i need to sort the distance and classified it to the nearest image.. – bohr Nov 15 '13 at 19:32
0

Besides the Map option, you can consider using some sort of Key value pair and, storing that in your array and sort your array based on the values.

See this for potential key value pairs, or make your own.

An example:

package com.example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class KeyValue {

    private int key;
    private Integer value;

    public KeyValue(int i, Integer j) {
        key  = i;
        value = j;
    }

    public static void main(String[] args) {

        List<KeyValue> arr = new ArrayList<KeyValue>();
        arr.add(new KeyValue(1, 100));
        arr.add(new KeyValue(2, 50));
        arr.add(new KeyValue(3, 10));
        Collections.sort(arr, new Comparator<KeyValue>(){

            @Override
            public int compare(KeyValue arg0, KeyValue arg1) {
                return Integer.compare(arg0.getValue(), arg1.getValue());
            }

        });
        for (KeyValue kv : arr){
            System.out.println(kv);
        }
    }

    public int getKey() {
        return key;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }

    @Override
    public String toString(){
        return "("+key+","+value.toString()+")";                
    }

}
Community
  • 1
  • 1
ljgw
  • 2,751
  • 1
  • 20
  • 39