1 package com.thaiopensource.validate.nrl; 2 3 class IntSet { 4 static private final int INIT_SIZE = 4; 5 private int[] v = null; 6 private int len = 0; 7 8 void add(int n) { 9 if (v == null) { 10 v = new int[INIT_SIZE]; 11 v[0] = n; 12 len = 1; 13 return; 14 } 15 if (len == v.length) { 16 int[] newv = new int[len*2]; 17 System.arraycopy(v, 0, newv, 0, len); 18 v = newv; 19 } 20 if (n > v[len - 1]) { 21 v[len++] = n; 22 return; 23 } 24 int i = 0; 25 for (; i < len; i++) { 26 if (n <= v[i]) { 27 if (n == v[i]) 28 return; 29 break; 30 } 31 } 32 for (int j = len; j >= i; j--) 33 v[j + 1] = v[j]; 34 v[i] = n; 35 ++len; 36 } 37 38 void addAll(IntSet is) { 39 if (is.len == 0) 40 return; 41 int[] newv = new int[len + is.len]; 42 int i = 0, j = 0, k = 0; 43 while (i < len && j < is.len) { 44 if (v[i] < is.v[j]) 45 newv[k++] = v[i++]; 46 else if (is.v[j] < v[i]) 47 newv[k++] = is.v[j++]; 48 else { 49 newv[k++] = v[i++]; 50 j++; 51 } 52 } 53 while (i < len) 54 newv[k++] = v[i++]; 55 while (j < is.len) 56 newv[k++] = is.v[j++]; 57 v = newv; 58 len = k; 59 } 60 61 int size() { 62 return len; 63 } 64 65 int get(int i) { 66 if (i >= len) 67 throw new IndexOutOfBoundsException (); 68 try { 69 return v[i]; 70 } 71 catch (NullPointerException e) { 72 throw new IndexOutOfBoundsException (); 73 } 74 } 75 } 76 | Popular Tags |