首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与不带数组的排序(ArrayList)做同样的事情?正在处理中

问与不带数组的排序(ArrayList)做同样的事情?正在处理中
EN

Stack Overflow用户
提问于 2012-10-02 11:00:04
回答 1查看 668关注 0票数 0

有没有办法对不在数组中的整数进行排序?

我知道你可以在数组中使用sort(arrayList)类型的想法,但是示例...

如果我有单独的变量,可以完成类似的任务吗?例如,如果我有三个数字,我可以对它们进行排序,使它们从大到小打印吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-03 08:03:10

如果您的ArrayList包含对象,则这些对象的类型可以实现Comparable,因此您可以使用Collections的sort方法。如果需要,可以将ArrayList转换为数组并按这种方式进行排序,但这看起来并不是您想要的。下面是一个使用这两种方法的快速示例:

代码语言:javascript
复制
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;    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12683985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档