总结两个向量

用户名

我可以知道如何在Java中对两个向量求和吗?

public void CosineSimilarity(ArrayList<Integer> h,String a, Object[] array) throws Exception { 
           Vector value  = new Vector();
           double cos_sim=(cosine_similarity(vec1,vec2))*60/100;
           System.out.println(cos_sim); //I get [0.333] and [0.358]
           value.add(cos_sim);   
           CompareType(value,a,array);
}

这里的CompareType函数

 public void CompareType(Vector value,String a,Object[] array ) throws Exception {
                // TODO Auto-generated method stub
                String k;
                double c = 0;
                String sql="Select Type from menu ";
                DatabaseConnection db = new DatabaseConnection();
                Connection  conn =db.getConnection();
                PreparedStatement  ps = conn.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                Vector value1 = new Vector();
                while (rs.next()) 
                {
                k=rs.getString("Type");
                if(a.equals(k))
                {
                    c=10.0/100;
                    value1.add(c);
                    }
                else
                {
                    c=0;
                    value1.add(c);  
                }
                 }
                System.out.println(value1); // I get [0.0] and [0.1]
                Sum(value,value1);

                ps.close();
                rs.close();
                conn.close();

            }

我应该在下面的函数中写些什么,以便可以将两个值向量相加并返回两个总值?

private void Sum(Vector value, Vector value1) {

        // TODO Auto-generated method stub

    }
斯拉蒂丹

使用Java8流API可以轻松实现(此示例代码输出6.01.0+2.0+3.0

/** setup test data and call {@link #sum(Vector)} */
public static void main(String[] args) {
    Vector a = new Vector();
    Vector b = new Vector();

    a.add(1.0);
    a.add(2.0);
    b.add(3.0);

    System.out.println(sum(a, b));
}

/** Sum up all values of two vectors */
private static double sum(Vector value, Vector value1) {
    return sum(value) + sum(value1);
}

/** Sum up all values of one vector */
private static double sum(Vector value) {
    return

            // turn your vector into a stream
            value.stream()

            // make the stream of objects to a double stream (using generics would
            // make this easier)
            .mapToDouble(x -> (double) x)

            // use super fast internal sum method of java
            .sum();
}

有关如何使代码更好的一些想法:

  • 使用泛型它们将帮助您避免强制转换,并且编译器将自动向您显示代码错误。
  • 有意义地命名您的变量和方法使用sumAandsumB代替sumand sum1,等等。
  • 使用Java编码约定(如方法名使用小写字母)。这将帮助其他Java开发人员更快地理解您的代码。
  • 接口和超类用作变量类型,返回类型和参数类型。这使您的代码具有更好的可重用性。在您的示例中使用CollectionList接口。
  • 使用java.util.ArrayList的赞成Vector(摘自官方javadoc:“如果不需要线程安全的实现,建议使用ArrayList代替Vector。”)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章