理解 Java 和泛型数组 [英] Understanding Java and Generic Arrays

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

问题描述

我正在尝试执行以下代码:

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];
    }
}

我的代码还有很多,但这些代码足以说明我的问题.当然,netbeans 显示了一个与通用数组有关的编译错误,在new 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.

网络上有很多关于编译器无法验证赋值类型的解释,如果你这样做,很多关于这个的问题就在 StackOverflow 上!也有一些方法可以解决这个问题,只要你向编译器展示你知道你在做什么!".问题是我无法让它工作,我无法理解解释,而且我真的想要一个数组列表.

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];

但它似乎无法正确投射,即使我看到的一个网站说你可以做这样的事情,或者使用@SuppressWarnings(unchecked")"和其他东西.拜托,我需要的方式比那些不太符合我的情况的例子更清楚,比如 这个解决方案,适用于地图,但不适用于 ArrayLists.

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.

像我在 StackOverflow 上的问题的其他答案可能确实很有帮助,但我不太了解它们,或者我不会写这个请求更接地气的东西.

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

.如果您确定这一点,那么您可以安全地取消警告.原则上使用泛型数组没有错.编译器只是保护您免于意外执行此类操作.

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天全站免登陆