在java中为泛型预定义乘法 [英] Predefining multiplication for generics in java

查看:156
本文介绍了在java中为泛型预定义乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,为了所有的意图和目的,我试图为自己实现一个java版本的C ++的STL算法inner_product作为矢量参数。到目前为止,我的代码(可能根本不对)看起来像这样:

  public static< T,K> double vector_product(Vector< T> v1,Vector< K> v2)
{
double isum = 0;
for(int i = 0; i< v1.size()& i< v2.size(); i ++)
{
isum + = v1.elementAt(i)* v2.elementAt(ⅰ);
}

return isum;
}

问题在于运算符*对于类型T,K未定义然而,迄今为止我的知识并不包括预定义的操作符,尽管据我所知在Java中也是不可能的。在实现采用泛型的功能方面,任何帮助都将受到赞赏。

解决方案

没有很好的方法来做到这一点,原因有两个:


  1. 类型参数( T K )必须参考对象类型,而不是原语。

  2. Java没有运算符重载。

可以得到像这样的东西(modulo语法错误,我的泛型生锈):

  public static< T extends Number,K extends数> double vector_product(Vector< T> v1,Vector< K> v2)
{
double isum = 0;
for(int i = 0; i< v1.size()& i< v2.size(); i ++)
{
isum + = v1.elementAt(i)。的doubleValue()* v2.elementAt(ⅰ).doubleValue();
}

return isum;
}

这适用于原始类型的对象包装,即 Double 但不是 double 等等。

另外,就像你的版本一样,这会返回 double ,无论传入哪种类型。由于类型擦除,这很难修复。


So I'm trying, for all intents and purposes, to realize for myself a java version of C++'s STL algorithm inner_product for vector parameters. So far, my code(which is probably fundamentally wrong) looks like this:

public static<T,K> double inner_product(Vector<T> v1, Vector<K> v2)
{
    double isum = 0;
    for(int i=0;i<v1.size()&&i<v2.size();i++)
    {
        isum+=v1.elementAt(i)*v2.elementAt(i);
    }

    return isum;
}

The problem is that the operator * is undefined for the types T, K. However my knowledge so far doesn't cover predefining operators, though as far as I know it's not possible in Java as well. Any help would be appreciated in the way of realizing the function to take generics. Thanks in advance.

解决方案

There is no nice way to do this, for two reasons:

  1. Type parameters (T, K) must refer to object types, not primitives.
  2. Java does not have operator overloading.

The closest you can get is something like this (modulo syntax errors, my generics are rusty):

public static<T extends Number,K extends Number> double inner_product(Vector<T> v1, Vector<K> v2)
{
    double isum = 0;
    for(int i=0;i<v1.size()&&i<v2.size();i++)
    {
        isum+=v1.elementAt(i).doubleValue()*v2.elementAt(i).doubleValue();
    }

    return isum;
}

This will work for the object wrappers around primitive types, i.e. Double but not double, etc.

Also, like your version, this returns double no matter what type was passed in. And because of type erasure, this is pretty hard to fix.

这篇关于在java中为泛型预定义乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆