java - add and increment array elements by arraycopy -


suppose array of object: element t[ ] , each object contains 2 integer variables (x,y).

t = (1,1) (2,2) (3,3) (4,4) 

i want increment value of variable x of object each time new element added array with faster way possible . new element can added in position , increment x element after insertion position (position +1)

before add (6,6) :

t = (1,1) (2,2) (3,3) (4,4)

after add (6,6) in different positions:

1) t = (6,6) (2,1) (3,2) (4,3) (5,4)

or

2) t = (1,1) (2,2) (6,6) (4,3) (5,4)

or

3) t = (1,1) (2,2) (3,3) (6,6) (5,4)

i used method arraycopy add new element, , loop for increment variable x each element, follow:

  1. increment x of object elements loop for

  2. ta[0] = (6,6)

  3. araycopy(t, 0, ta, 1, t.size-1 );

because faster

while (i< t.length){    t[i] = t[i+1]    t[i].x ++;     i++; } 

i need add new element , increment other objects of array simultaneously faster time.

//-------------------

public class elemt {

public int x; public int y;  public elemt(int a, int b){     this.x= a;     this.y= b; }   public void inc(){  x++; }  int getx(){     return x; }  int gety(){     return y; } 

}

//----------------

public class tad {

public static arraylist < elemt > t = new arraylist < elemt > ( );

public static arraylist < elemt > t1 = new arraylist < elemt > ( );

 public static void main(string[] args){        for(int i=0; i<10000000; i++){        t1.add(new elemt(i, i));       }        long t0 = system.currenttimemillis();        t1.add(0, new elemt(1, 1));       long t1= system.currenttimemillis()- t0;       system.out.println("time without incrementation : "+t1);    //--------------       for(int i=0; i<10000000; i++){        t.add(new elemt(i, i));       }       long t2 = system.currenttimemillis();         t.add(0, new elemt(1, 1));          for(int i=1; i<t.size(); i++){           t.get(i).inc();         }      long t3= system.currenttimemillis()- t2;    system.out.println("time incrementation: "+t3);     } 

//------- results:

time without incrementation : 15 ms

time incrementation: 156 ms

my objective minimize possible time of incrementation process

(time incrementation < time without incrementation * 2 )

because actually

time incrementation (156 ms) = time without incrementation (15 ms )* 10

i notes can added new element in position, chose worst case (adding element in first position requires incrementation of x element of arraylist)

don't use array, use deque, linkedlist. has o(1) insertion @ front time.

public void addandincrement(deque<point> deque, point new) {   for(point p : deque) {     p.x++;   }    deque.addfirst(new); } 

or something.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -