difference of two consecutive values in an ArrayList: Android

I have an ArrayList() which stores some data generated at real time. I want to get the difference of the consecutive element of the ArrayList

  1. I tried this

    ArrayList<Long> difference = new ArrayList<>();
    difference.add(durationInMs);
    //tried to store 
    for (int d = 0; d < difference.size()-1; d++){
            time1 = difference.get(d);
            time2 = difference.get(d + 1);
            timeDifference = time2 - time1;
    }
    
  2. This

    ArrayList difference = new ArrayList<>(); difference.add(durationInMs);

    ArrayList<Long> tempArray = new ArrayList<>();
    tempArray.add(0, difference.get(0));
    
    for (int d = 0; d < difference.size()-1; d++){
            timeDifference = tempArray.get(d+1) - difference.get(d);
    }
    Log.d("time", String.valueOf(timeDifference));
    
  3. Also this enter link description here

But non of them seems to get me the subtracted value between 2 consecutive elements. Probably the problem is the values are generating in real time and this when subtracting, the next value is not yet generated. How do i do it?

Try:

for (int d = 0; d < difference.size()-1; d++){
    Log.i("diff", String.format(
        "element %d,%d:%d - %d = %d",
        d+1, d, difference.get(d+1), difference.get(d),
        difference.get(d+1) - difference.get(d));
}

How about this? At the time a new data point is generated, could you look at the prior data point and calculate delta on-the-fly, then add() the delta to another array?

  long lastDatum = null;
  ArrayList<long> diffArray = new ArrayList<>();

  void recordDataPoint(long datum)
  { 
      if (lastDatum != null) {
         diffArray.add(datum - lastDatum);
      }
      lastDatum = datum;

      // ... do whatever else you need to do with datum....
   }

0 Comment

NO COMMENTS

LEAVE A REPLY

Captcha image