开发者

can i use generic for float[] and int[]?

开发者 https://www.devze.com 2023-03-05 22:40 出处:网络
we have two process classes which are almost identical except One is used to pro开发者_JAVA技巧cess a float[] data and another is for a int[] data.

we have two process classes which are almost identical except One is used to pro开发者_JAVA技巧cess a float[] data and another is for a int[] data.

I am thinking to combine them into one. My original thinking is use generic for float[] and int[].

Java generic is new to me. So I wrote the following test method to see how generic works but I cannot make it working for me.

public <T> T caculate(T[] values)
    {
        T result;
        for(int i = 0; i < values.length; i++)
        {
            result = result + values[i];
        }

        result = result/(values.length);
        return result;       
    }

Anybody can modify above method for me? float and int is primitive type in Java. Probably above method is not right.


We have two process classes which are almost identical except One is used to process a float[] data and another is for a int[] data.

Unfortunately, you can't do that with generics. Your best options is to bite the bullet and code the two classes separately; i.e. no generics.

In theory, you could try changing the arrays to Integer[] and Float[] and changing <T> to <T extends Number>. However:

  • This liable to involve changing other parts of your code.

  • It is liable to make your processing code slower.

  • It will probably be difficult to express your processing algorithm in a generic way using T extends Number. For a start, the Number interface doesn't support arithmetic.


I guess it would also be possible to solve this problem by wrapping the primitive arrays in some class that makes them look like arrays of (say) integers. But that is liable to give you problems with truncation, precision and so on ... depending on the algorithms you are implementing. So this will only work in limited cases.


Your method doesn't work because you are trying to apply the + operator to objects of type T. However, there's no guarantee that T will support that operation, so the compiler won't let you do it. Unfortunately, there isn't a constraint you could put on the generic type that would correct this issue.

If you want to process both int[] and float[] with one method, just do everything with floats and cast the ints as needed.

0

精彩评论

暂无评论...
验证码 换一张
取 消