1 package prefuse.util.collections; 2 3 import java.io.ByteArrayInputStream ; 4 import java.io.InputStream ; 5 6 11 public class ByteArrayList { 12 13 private byte[] m_bytes; 14 private int m_size; 15 16 public ByteArrayList() { 17 this(4096); 18 } 19 20 public ByteArrayList(int capacity) { 21 m_bytes = new byte[capacity]; 22 m_size = 0; 23 } 24 25 private void rangeCheck(int i) { 26 if ( i < 0 || i >= m_size ) 27 throw new IndexOutOfBoundsException ( 28 "Index: "+i+" Size: " + m_size); 29 } 30 31 private void ensureCapacity(int cap) { 32 if ( m_bytes.length < cap ) { 33 int capacity = Math.max((3*m_bytes.length)/2 + 1, cap); 34 byte[] nbytes = new byte[capacity]; 35 System.arraycopy(m_bytes, 0, nbytes, 0, m_size); 36 m_bytes = nbytes; 37 } 38 } 39 40 public byte get(int i) { 41 rangeCheck(i); 42 return m_bytes[i]; 43 } 44 45 public void set(int i, byte b) { 46 rangeCheck(i); 47 m_bytes[i] = b; 48 } 49 50 public int size() { 51 return m_size; 52 } 53 54 public void add(byte b) { 55 ensureCapacity(m_size+1); 56 m_bytes[m_size++] = b; 57 } 58 59 public void add(byte[] b, int start, int len) { 60 ensureCapacity(m_size+len); 61 System.arraycopy(b,start,m_bytes,m_size,len); 62 m_size += len; 63 } 64 65 public InputStream getAsInputStream() { 66 return new ByteArrayInputStream (m_bytes,0,m_size); 67 } 68 69 public byte[] toArray() { 70 byte[] b = new byte[m_size]; 71 System.arraycopy(m_bytes,0,b,0,m_size); 72 return b; 73 } 74 } 75 | Popular Tags |