了解Java和通用阵列 [英] Understanding Java and Generic Arrays

查看:81
本文介绍了了解Java和通用阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试做以下code:

I am trying to do the following code:

public class AddressManager
{
    private ArrayList<Address>[] array;
    private int depth;

    public AddressManager(int d, int s, Address a)
    {
        array = new ArrayList<Address>[d];
    }
}

有更多的是我的code,但code的这一数额足以说明我的问题。当然,NetBeans的显示编译错误做普通阵列,就符合新的ArrayList ......,而我有很多读了这一点。

There is more to my code, but this amount of code is sufficient to show my problem. Of course, netbeans shows a compile error to do with generic arrays, on the line with "new ArrayList...", and i have read up alot about this.

有解释相关所有网站上说明有关无法验证类型的任务,如果你这样做,编译器的事情,许多问题这个是这里的计算器!也有所谓的方法来解决这个问题,只要你表现出编译器你知道你在做什么!。问题是,我不能得到这个工作,我无法理解的解释,我真的想的ArrayList的数组。

There are explainations all over the web stating things about the compiler not being able to verify types in assignments if you do this, and lots of questions about this are right here on StackOverflow! There are also supposedly ways to work around this, so long as you show the compiler that "You know what you're doing!". The issue is that i can't get this to work, i can't understand the explanations, and i really do want an array of arraylists.

可能有人请更简单的语言解释我能做些什么来解决这个错误在我的特殊情况?我曾尝试某种想法如下:

Could someone please explain in more simple language what i can do to get around this error in my specific case? I have tried the following sort of idea:

private Object[] array;
array = (ArrayList<Address>[]) new Object[d];

但似乎不能正确地投,即使网站我看到说你可以做这样的事情,或使用@燮pressWarnings(未登记)的东西或其他的之一。拜托,我需要这样的方式比不太我的情况像相匹配的这个解决方案,这对于地图的伟大工程,但不是的ArrayList

But it seems it can not be cast correctly, even though one of the sites i saw said you could do something like this, or use "@SuppressWarnings("unchecked")" with something or other. Please, i need this in a way that is more clear than examples that don't quite match my situation like This solution, which works great for maps, but not ArrayLists.

其他答案的问题,就像在计算器上雷可能确实是非常有用的,但我不明白他们很好,否则我就不会写一些更脚踏实地的这一请求。

The other answers to questions just like mine on StackOverflow may be very helpful indeed, but i do not understand them very well, or i would not be writing this request for something more down to earth.

推荐答案

有什么错如下:

@SuppressWarnings("unchecked")
ArrayList<Address>[] array = (ArrayList<Address>[]) new ArrayList<?>[d];

您只需要确保你真的只存储的ArrayList&LT;地址&gt; 的数组中为止。如果你是肯定的,那么你可以放心地燮preSS的警告。有没有错,原则上使用通用阵列。编译器只是保护你做这样的事情意外。

You just need to be sure that you really are only storing ArrayList<Address> in the array. If you are sure of that, then you can safely suppress the warning. There's nothing wrong with using generic arrays in principle. The compiler is just protecting you from doing something like this accidentally.

这篇关于了解Java和通用阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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