0

配列にない int をソートする方法はありますか?

sort(arrayList)配列で型アイデアを使用できることは知っていますが、例...

個々の変数がある場合、同様のタスクを実行できますか? たとえば、数字が 3 つある場合、大きいものから小さいものへと並べ替えることができますか?

ありがとう!

4

1 に答える 1

1

ArrayList がオブジェクトを保持している場合、それらのオブジェクトの型はComparableを実装できるため、Collectionsの sort メソッドを使用できます。必要に応じて、ArrayList を配列に変換し、そのように並べ替えることができますが、それは望んでいるようには見えません。両方の方法を使用した簡単な例を次に示します。

void setup(){
  int count = 100,now;
  stroke(192,0,0);strokeWeight(count/width);
  //make up some data
  ArrayList<Pair> p = new ArrayList<Pair>();
  for(int i = 0 ; i < count ; i++) {
    Pair pair = new Pair(i,random(10,100));
    p.add(pair);
    float x = map(i,0,count,i,width);
    float y = map(pair.distance,10,100,0,50);
    line(x,50,x,50-y);
  }

  now = millis();

  //Sort typed ArrayList by converting to array first
  println("sort typed array: \n");
  Pair[] s = new Pair[p.size()];
  p.toArray(s);
  Arrays.sort(s);

  println("took " + (millis()-now) + " ms");

  now = millis();

  //Sort using Collections
  println("\n\nsorting typed array list: \n" );
  Collections.sort(p);

  println("took " + (millis()-now) + " ms");

  stroke(0,192,0);
  for(int i = 0 ; i < count ; i++) {
    Pair pair = p.get(i);
    float x = map(i,0,count,i,width);
    float y = map(pair.distance,10,100,0,50);
    line(x,100,x,100-y);
  }

}
class Pair implements Comparable<Pair>{
  public int id;
  public float distance;
  Pair(int i, float d){
    id = i;
    distance = d;
  }
  int compareTo(Pair p){
    if     (p.distance > this.distance) return  1;
    else if(p.distance < this.distance) return -1;
    else return 0;
  }
  String toString(){    return id+":"+distance;    }
}
于 2012-10-03T00:03:10.193 に答える