简体   繁体   English

实例化Java中的通用Number类

[英]Instantiate a generic Number class in Java

I am trying to create an Array-like object that can store Number types. 我试图创建一个可以存储Number类型的类似Array的对象。 I want to initialize each value in Object[] array to 0 . 我想将Object[] array每个值初始化为0 If I knew that the NegativeArray was storing Integer s, then I could do new Integer(0) . 如果我知道NegativeArray正在存储Integer ,则可以执行new Integer(0) Unfortunately, when dealing with the generic type E , I don't know how to create a new Number with value 0 . 不幸的是,当处理通用类型E ,我不知道如何创建一个值为0的新Number

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. 您需要的不仅仅是E :您需要一个单独的合同,其中说E具有getZero()方法,或者您需要单独接受getZero方法。

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. 在Java 8中,除了构造函数中的其他参数之外,您还可以接受Supplier< E > ,并且可以为通用Number子类提供一些stock Supplier

In Java 7 and earlier, you can manually define the ZeroSupplier<E> interface. 在Java 7和更早版本中,您可以手动定义ZeroSupplier<E>接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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