假設一個對象數組:Element T [],每個對象包含兩個整數變量(x,y)。通過arraycopy增加和增加數組元素
T = (1,1) (2,2) (3,3) (4,4)
欲增加一個新元素被添加到陣列具有可能的更快的方式可變對象的X每個時間的值。新元素可以在任何位置添加我們增加插入位置畢竟X元素(位置+1)
加前(6,6):
T = (1,1) (2,2) (3,3) (4,4)
後添加( 6,6)在不同的位置:
1)T = (6,6)(,1)(3 ,2)(4 ,3)(5 ,4)
或
2)T =(1,1)(2,2)(6,6)(,3)(,4)
或
3)T =(1,1)(2,2)(3,3)(6,6)(,4)
我用arraycopy添加新元素的方法,以及環爲遞增變量X每個元素,如下:
增量與循環對象元素的所有
x
對於Ta[0] = (6,6)
araycopy(T, 0, Ta, 1, T.size-1);
,因爲它的速度比
While (i< T.length){
T[i] = T[i+1]
T[i].x ++;
i++;
}
我需要一個更快的時間同時添加新元素,並增加陣列的其他對象。
// -------------------
公共類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;
}
}
// --- -------------
公共類TAD {
公共靜態的ArrayList < elemt> T =新的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 with Incrementation: "+t3);
}
// -------結果:
時間沒有增量方向:15毫秒
時間與增量方向:156毫秒
我的目標是儘可能減少增量過程的時間
(時間增量<時間無增量* 2)
因爲實際上
與增量方向(156毫秒)=時間時間沒有增量方向(15毫秒)* 10
我注意到,我可以在任何位置添加了新的元件,但我選擇最壞的情況下(添加在所述第一位置,需要該ArrayList所有X元件的增量的元件)
可以使用列表,存在插入的對象的列表的開頭()稱爲addfirst僅一個方法..和比可以從第二元件迭代列表,並遞增變量X – Elior 2013-05-02 19:54:11