简体   繁体   中英

Instantiate a generic Number class in Java

I am trying to create an Array-like object that can store Number types. I want to initialize each value in Object[] array to 0 . If I knew that the NegativeArray was storing Integer s, then I could do new Integer(0) . Unfortunately, when dealing with the generic type E , I don't know how to create a new Number with value 0 .

This is my current implementation:

package com.gly.sfs.util;

public class NegativeArray <E extends Number> {

    private int firstIndex;
    private int lastIndex;
    private Object[] array;

    public NegativeArray(int firstIndex, int lastIndex) {
        this.firstIndex = firstIndex;
        this.lastIndex = lastIndex;

        boolean isValid = lastIndex > firstIndex; 
        if (!isValid) {
            throw new IllegalArgumentException(
                    "lastIndex > firstIndex violated!");
        }

        array = new Object[size()];
    }

    public void set(int index, E e) {
        checkIndexValidity(index);
        array[getIndex(index)] = e;
    }

    public E get(int index) {
        checkIndexValidity(index);
        @SuppressWarnings("unchecked")
        E e = (E) array[getIndex(index)];
        return e;
    }

    public int size() {
        return lastIndex - firstIndex;
    }

    private int getIndex(int index) {
        return index - firstIndex;
    }

    private void checkIndexValidity(int index) {
        boolean isValid = (index >= firstIndex) & 
                (index < lastIndex);
        if (!isValid) {
            throw new ArrayIndexOutOfBoundsException();
        }
    }
}

You need more than E : you either need a separate contract that says E has a getZero() method, or you need to accept a getZero method separately.

In Java 8 you can accept a Supplier< E > in addition to the other arguments in your constructor, and you can have a few stock Supplier s around for the common Number subclasses.

In Java 7 and earlier, you can manually define the ZeroSupplier<E> interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM