Пример #1
0
 /** Convert a dense array to a sparse array */
 public static SparseIntArray fromArray(int[] arr) {
   SparseIntArray sa = new SparseIntArray(arr.length);
   for (int i = 0; i < arr.length; i++) {
     if (arr[i] != 0) {
       sa.put(i, arr[i]);
     }
   }
   return sa;
 }
Пример #2
0
 /**
  * Create a new sparse integer array of length n
  *
  * @param n The length of the array
  * @param defaultValue The default value (e.g., 0.0)
  * @param values The values as key,value pairs
  * @throws IllegalArgumentException If the length of values is not a multiple of two
  */
 public SparseIntArray(int n, int defaultValue, int... values) {
   this.n = n;
   this.defaultValue = super.defRetValue = defaultValue;
   if (values.length % 2 != 0) {
     throw new IllegalArgumentException("Wrong number of varargs to SparseIntArray");
   }
   for (int i = 0; i < values.length; i += 2) {
     put(values[i], values[i + 1]);
   }
 }
Пример #3
0
 @Override
 public Vector<Integer> subvector(int offset, int length) {
   final SparseIntArray sv = new SparseIntArray(n);
   final ObjectIterator<Entry> iter = int2IntEntrySet().fastIterator();
   while (iter.hasNext()) {
     final Entry e = iter.next();
     if (e.getIntKey() >= offset && e.getIntKey() < offset + length) {
       sv.put(e.getIntKey(), e.getIntValue());
     }
   }
   return sv;
 }
Пример #4
0
 /**
  * Create from a string of the form "idx=val,...,idx=val"
  *
  * @param string The string
  * @param n The length of the array
  * @param defaultValue The default value
  * @param sep The seperator
  * @return The array object
  * @throws SparseIntArrayFormatException If the string is not formatted as a sparse array
  */
 public static SparseIntArray fromString(String string, int length, int defaultValue, String sep)
     throws VectorFormatException {
   String[] entries = string.split(sep);
   final SparseIntArray SparseIntArray = new SparseIntArray(length);
   for (String entry : entries) {
     if (entry.matches("\\s*")) {
       continue;
     }
     String[] values = entry.split("=");
     if (values.length != 2) {
       throw new VectorFormatException("Bad sparse array value " + entry);
     }
     SparseIntArray.put(new Integer(values[0]), new Integer(values[1]));
   }
   return SparseIntArray;
 }