gpt4 book ai didi

java - 总结两个 vector

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:08 27 4
gpt4 key购买 nike

我可以知道如何在 java 中对两个 vector 求和吗?

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();

}

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

private void Sum(Vector value, Vector value1) {

// TODO Auto-generated method stub

}

最佳答案

使用 Java8 流 API 很容易(此示例代码输出 6.0 作为 1.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();
}

关于如何使您的代码变得更好的一些想法:

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

关于java - 总结两个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32165433/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com