Peter February 2016

Changing the type of primitive arrays in Java

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>).

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.

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

Answers


cldjr February 2016

Do you really need to deal with primitive types only? If not, you could consider having an array of Number - this way you can instantiate either a Float[] or Double[].

Number numbers[] = (param == "float" ? new Float[n] : new Double[n]);

I assume using wrappers is less efficient than using primitives (I haven't benchmarked though) but it's sure faster than using Collections (eg ArrayList).


Frank February 2016

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.

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

Post Status

Asked in February 2016
Viewed 3,307 times
Voted 4
Answered 2 times

Search




Leave an answer