Tuesday, November 25, 2014
vector implementation using array -- Java
public class ImpArrayList {
private int[] m_data = null;
private int m_cur_size = -1;
private int m_total_size = -1;
private static final int s_min_size = 8;
public ImpArrayList(int sz) {
if(sz < 0) {
sz = 0;
}
m_total_size = sz*2;
if(m_total_size < s_min_size) {
m_total_size = s_min_size;
}
m_data = new int [m_total_size];
m_cur_size = sz;
}
public ImpArrayList() {
this(0);
}
public int get(int i) {
return m_data[i];
}
public void set(int i, int v) {
m_data[i] = v;
}
public void push_back(int v) {
if(m_cur_size >= m_total_size) {
m_total_size = m_total_size * 2;
int [] tmp = new int [m_total_size];
System.arraycopy(m_data, 0, tmp, 0, m_cur_size);
m_data = tmp;
}
m_data[m_cur_size] = v;
m_cur_size++;
}
public void pop_back() {
m_cur_size--;
if(m_cur_size < 0) {
//should throw an exception
m_cur_size = 0;
}
}
public boolean empty() {
return m_cur_size == 0;
}
//some other functions like resize ...
public static void main(int argc, String[] argv){
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment