有关基本数组的Java泛型方法代码重复问题 [英] Java Generics method code duplication issue regarding primitive arrays

查看:62
本文介绍了有关基本数组的Java泛型方法代码重复问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在为一个小型个人实用程序库实现Grid类的实现。完成大量工作后,我将整理Grid类并添加一些功能。我希望与Grid类一起使用的关键功能之一就是能够将任意给定类型的单个2D数组作为构造函数的参数。

So I'm working on an implementation of a Grid class for a small, personal utilities library. After much work, I'm tidying up the Grid class and adding some functionality. One of the key pieces of functionality that I wish to use with my Grid class is to be able to take a single, 2D array of any given type as an argument to the constructor.

这很好用,直到我意识到我无法编译任何试图将任何原语数组传递给构造函数的代码。由于自动装箱不会在原始数组上发生,因此这以代码重用的形式向我提出了一个设计问题。不管传入的数组类型如何,初始化Grid的方法都是相同的,即使它们是基元,但似乎我需要为所有不同类型的基元编写一个单独的构造函数。假设我只使用基本的构造函数,这给我留下了9个不同的构造函数(并且我曾计划让构造函数使用诸如网格包装选项之类的不同参数)。

This worked fine until I realized that I can't compile any code that attempts to pass in any array of primitives to the constructor. Since autoboxing doesn't happen on primitive arrays, this presents a design problem to me in the form of code reuse. The method for initializing the Grid is the same regardless of the type of array passed in, even if they are primitives, but it appears that I need to write a separate constructor for all the different types of primitives. Which leaves me with 9 different constructors assuming I just use my base constructor (and I had planned to have constructors with different arguments for things such as grid-wrapping options).

我是正确的假设没有办法避免所有这些代码重复吗?

Am I right in assuming that there is no way to avoid all this code duplication?

推荐答案

您可以使用 Array 避免(大部分)重复类。但这不是很漂亮:您的构造函数参数的类型肯定是 Object ,并且您只需要相信调用方可以在其中传递实际的数组,而不是套接字属性

You can avoid (most of) the duplication by using Array class. But it's not pretty: your constructor parameter would have do be of type Object, and you'd have to just trust your caller to pass the actual array there, and not a Socket or a Properties.

例如,您可以这样进行自己的拳击:

For example, you could do your own boxing like this:

<T> public T[][] boxArray(Class<T> clazz, Object array) {
    int height = Array.getLength(array);
    int width = height == 0 ? 0 : Array.getLength(Array.get(array, 0));
    T[][] result = (T[][]) Array.newInstance(clazz, height, width);
    for(int i = 0; i < height; i ++) {
        Object a = Array.get(array, i);
        for(int j = 0; j < width; j++) {
            result[i][j] = (T) Array.get(a, j); 
        }
    }
    return result;
}

这篇关于有关基本数组的Java泛型方法代码重复问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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