オブジェクト配列へのデータ追加・削除およびデフラグ

  • タグ:
  • タグはありません
public class Sample {
    private Object[] array;
    private int[] stack;
    private int sp;
    
    public Sample(int size){
        array = new Object[size];
        stack = new int[size + 1];
        sp = 0;
        stack[0] = 0;
    }
    
    public void add(Object obj){
        if(stack[sp] >= array.length) return;
        array[stack[sp]] = obj;
        if(sp == 0){
            stack[sp]++;
        }else{
            sp--;
        }
    }
    
    public Object get(int index){
        if(index >= 0 && index < array.length){
            return array[index];
        }else{
            return null;
        }
    }
    
    public Object remove(int index){
        if(index < 0 || index >= array.length || array[index] == null) return null;
        Object obj = array[index];
        array[index] = null;
        stack[++sp] = index;
        return obj;
    }
    
    public void defrag(){
        int ptr = stack[0] - 1;
        while(sp > 0 && ptr >= 0){
            if(array[ptr] != null){
                if(stack[sp] < ptr){
                    Object tmp = array[ptr];
                    array[ptr] = array[stack[sp]];
                    array[stack[sp]] = tmp;
                    ptr--;
                }
                sp--;
            }else{
                ptr--;
            }
        }
        sp = 0;
        stack[0] = ptr >= 0 ? ptr + 1 : 0;
    }
}