【问题标题】:Using processing js and java arraylist sort使用处理js和java arraylist排序
【发布时间】:2015-02-17 09:46:21
【问题描述】:

我正在处理中实现一些光线跟踪,并且正在使用数组列表来对交叉点进行排序并创建一个遮罩。现在我想使用处理js将这些草图上传到网络上。在我实现 arraylist 之前,我已经尝试上传草图并且它们起作用了。

相关代码如下:

 import java.util.*; 
   ArrayList<Intersection> myIntersects; 

   void setup(){ 
   myIntersects = new ArrayList<Intersection>(); 

   //some code initializing the intersections and adding them to the arraylist
   }

   void draw(){
   Collections.sort(myIntersects); 
   }

   class Intersection implements Comparable<Intersection> {
   float angle; 

   //constructor and other functions

   public int compareTo(Intersection intersect){ 
   int result = 0; 
   float temp = angle - intersect.angle;
   if (temp < 0){ 
       result = -1; 
   } else if (temp > 0){
       result = 1; 
   } else {
       result = 0; 
   }
   return result; 
}

有没有办法对处理js允许的交叉点进行排序? (或者可能是处理 js 的扩展,以便允许排序)

感谢您的帮助。

【问题讨论】:

    标签: java sorting arraylist processing


    【解决方案1】:

    JavaScript 数组已经很灵活了,所以你真的不需要 ArrayList 类。只需使用 Array.push() 函数即可。

    JavaScript 数组还有一个 sort() 函数,它接受一个比较函数的可选参数。

    您的代码可能如下所示:

    var myIntersects = [];
    myIntersects.push(intercept1);
    myIntersects.push(intercept2);
    myIntersects.sort(function(a, b){
    int result = 0; 
       float temp = a.angle - b.angle;
       if (temp < 0){ 
           result = -1; 
       } else if (temp > 0){
           result = 1; 
       } else {
           result = 0; 
       }
       return result; 
    });
    

    更多信息在这里:http://www.w3schools.com/jsref/jsref_sort.asp

    【讨论】:

    • 谢谢,我会尝试改用javascript数组。
    • @Bluefarmer 如果您使用的是 Processing.js,那么您已经在使用 JavaScript 数组了。您只是没有充分发挥它们的潜力。
    猜你喜欢
    • 1970-01-01
    • 2010-12-03
    • 2020-05-25
    • 2011-08-18
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    相关资源
    最近更新 更多