在Java中更改基本数组的类型 [英] Changing the type of primitive arrays in Java

查看:161
本文介绍了在Java中更改基本数组的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字程序在Java中对原始数组执行了很多操作。我使用原始数组( double [] / float [] / int [ code>),因为它们比处理指向值的指针数组(例如 ArrayList< Float> )更多的内存和时间效率。

I have a numeric program in Java that does a lot of operations on primitive arrays. I use primitive arrays (double[]/float[]/int[]) because they are much more memory and time-efficient than dealing with arrays of pointers to values (e.g. ArrayList<Float>).

现在,我想要能够更改我的原始类型,例如。从double到float,基于一些参数给我的程序。但是因为原始的不能用作泛型,我不能为我的生活弄清楚如何。

Now, I want to be able to change my primitive type, eg. from double to float, based on some parameter to my program. But since primitive can not be used as generics, I can't for the life of me figure out how.

有什么办法,或者是大量的代码复制或者转换我只能做一个不可避免的Java缺陷吗?

Is there any way, or is the vast amount of code replication or casting I have to do just an unavoidable flaw of Java?

推荐答案

这是一个可能实现的包装类:

Here's a possible implementation of a wrapper class:

public class NumberListWrapper<T extends Number> {
    private ArrayList<T> numbers = new ArrayList<>();

    public boolean add(T num) {
        return numbers.add(num);
    }

    public boolean contains(T num) {
        return numbers.contains(num);
    }

    public boolean remove(T num) {
        return numbers.remove(num);
    }

    public float[] toFloatArray() {
        float[] floats = new float[numbers.size()];

        for(int i = 0; i < numbers.size(); i++) {
            floats[i] = numbers.get(i).floatValue();
        }

        return floats;
    }
}

其他原始数组转换使用与此浮点型相同的模式一个。

Other primitive array conversions use the same pattern as this float one.

编辑:你可能想要一个get()方法... lol

You probably want a get() method too... lol

这篇关于在Java中更改基本数组的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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