示例#1
0
  /**
   * Creates a copy of a given {@code DoubleVector} with the same type as the original.
   *
   * @param source The {@code Vector} to copy.
   * @return A copy of {@code source} with the same type.
   */
  public static DoubleVector copyOf(DoubleVector source) {
    if (source == null) return null;
    DoubleVector result = null;

    if (source instanceof SparseDoubleVector) {
      result = new CompactSparseVector(source.length());
      copyFromSparseVector(result, source);
    } else if (source instanceof DenseVector || source instanceof ScaledDoubleVector) {
      result = new DenseVector(source.length());
      for (int i = 0; i < source.length(); ++i) result.set(i, source.get(i));
    } else if (source instanceof AmortizedSparseVector) {
      result = new AmortizedSparseVector(source.length());
      copyFromSparseVector(result, source);
    } else if (source instanceof DoubleVectorView) {
      DoubleVectorView view = (DoubleVectorView) source;
      return copyOf(view.getOriginalVector());
    } else {
      // Create a copy of the given class using reflection.  This code
      // assumes that the given implemenation of Vector has a constructor
      // which accepts another Vector.
      try {
        Class<? extends DoubleVector> sourceClazz = source.getClass();
        Constructor<? extends DoubleVector> constructor =
            sourceClazz.getConstructor(DoubleVector.class);
        result = (DoubleVector) constructor.newInstance(source);
      } catch (Exception e) {
        throw new Error(e);
      }
    }
    return result;
  }
示例#2
0
 /**
  * Copies values from a {@code SparseVector} into another vector
  *
  * @param destination The {@code Vector to copy values into.
  * @param source The {@code @SparseVector} to copy values from.
  */
 private static void copyFromSparseVector(DoubleVector destination, DoubleVector source) {
   int[] nonZeroIndices = ((SparseVector) source).getNonZeroIndices();
   for (int index : nonZeroIndices) destination.set(index, source.get(index));
 }