向下转换Java中的数组(去掉选中警告游戏) [英] downcasting an array in java (remove the unchecked warning game)

查看:136
本文介绍了向下转换Java中的数组(去掉选中警告游戏)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个愚蠢的愚蠢的问题,但有时你必须要问他们反正。

我在我的左手有一个Object []实例(它来自非通用摆动)和接受的方法的假设整数[]作为其参数(在我的情况下,它实际上是一个可变参数)在我的右手。我敢肯定,阵列的内容(或者我已经准备好要付出的代价,如果我错了)。

所以基本上我写的:

 私有静态< U,T扩展了U> T []投(最终U []输入,最后一类< T> NEWTYPE){
    // noinspection选中
    最后T []结果=(T [])Array.newInstance(NEWTYPE,input.length);
    System.arraycopy(输入,0,结果,0,input.length);
    返回结果;
}

你能删除选中的警告,没有拔下呢?

为什么没有Array.newInstance()被泛型化?


解决方案

  

为什么没有Array.newInstance()被泛型化?


这可能与仿制药仅被引用类型实现的。 Array.newInstance(int.class,42)是完全合法的,类< INT> 不是。有了这种限制,有没有把它输入通用的向后兼容的方​​式。

java.util.Arrays中的类的工作这一轮通过对每个原始类型提供了多个重载。所以这个作品:

 私有静态< U,T扩展了U> T []投(最终U []输入,最后T []原型){
    最后T []结果= Arrays.copyOf(原型,input.length);
    System.arraycopy(输入,0,结果,0,input.length);
    返回结果;
}

如果你不介意传递一个空数组,而不是类对象,它避免了偏色。

I have a dumb silly question, but sometimes you have to ask them anyways.

I got an Object[] instance in my left hand (it comes from non-generic swing) and a method that accepts a let's say Integer[] as its argument (in my case it's actually a vararg) in my right hand. I'm sure of the content of the array (or I'm ready to pay the price if I'm wrong).

So basically I wrote that :

private static <U, T extends U> T[] cast(final U[] input, final Class<T> newType) {
    //noinspection unchecked
    final T[] result = (T[]) Array.newInstance(newType, input.length);
    System.arraycopy(input, 0, result, 0, input.length);
    return result;
}

can you remove the unchecked warning, without unplugging it ?

why haven't Array.newInstance() been genericized ?

解决方案

why haven't Array.newInstance() been genericized ?

It may be related to generics only being implemented for reference types. Array.newInstance( int.class, 42 ) is perfectly legal, Class<int> is not. With that limitation, there wasn't a backwards compatible way of making it type generic.

The java.util.Arrays class works round this by providing multiple overloads for each primitive type. So this works:

private static <U, T extends U> T[] cast ( final U[] input, final T[]  prototype ) {
    final T[] result = Arrays.copyOf ( prototype, input.length );
    System.arraycopy(input, 0, result, 0, input.length);
    return result;
}

If you don't mind passing in an empty array instead of the class object, it avoids the cast.

这篇关于向下转换Java中的数组(去掉选中警告游戏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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