消除 List>.toArray() 中的警告

发布于 2024-10-07 14:13:14 字数 366 浏览 5 评论 0 原文

另一种是我如何在没有警告问题的情况下执行 toArray() ,但它与此处发布的大多数问题不同。

如何重写方法实现(不更改方法签名)以使其在没有警告的情况下进行编译?

这里明显的困难是 T 的类信息在运行时不可用。但是,返回类型在运行时也是被擦除的类型,因此没有真正的理由不能这样做。那么,如果想强制执行编译时类型安全,我该怎么做呢?

谢谢

<T> GenericClass<T>[] toGenericArray(List<GenericClass<T>> list) {
    return list.toArray(new GenericClass[0]);
}

Another one of those how do I do toArray() with no warnings questions, but it's different from most of the ones posted here.

How do I rewrite the method implementation (without changing the method signature) to make it compile without warning?

The apparent difficulty here is that the Class information for T is not available during runtime. However, the return type is an erased type during runtime too, so there's no really reason that this cannot be done. So, how do I do this if want to enforce compile-time type safety?

Thank you

<T> GenericClass<T>[] toGenericArray(List<GenericClass<T>> list) {
    return list.toArray(new GenericClass[0]);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

变身佩奇 2024-10-14 14:13:14

你不能。由于数组是协变的,因此保存参数化类型的数组不可能具有编译时安全性。 (除非您使用 < ? > 这是合法的。)

这将始终是合法的:

GenericClass<String>[] array = new GenericClass[1];
Object[] brokenArray = array;
brokenArray[0] = new GenericClass<Integer>();
String value = array[0].getGenericValue(); //kaboom

编译器无法保护您免受这种情况的影响,因此它迫使您承认/禁止存在警告。

You can't. Because Arrays are covariant, it is impossible to have compile time safety for an array that's holding a parameterized type. (unless you use < ? > which is legal.)

This will always be legal:

GenericClass<String>[] array = new GenericClass[1];
Object[] brokenArray = array;
brokenArray[0] = new GenericClass<Integer>();
String value = array[0].getGenericValue(); //kaboom

Compiler is unable to protect you from that, so it forces you to acknowledge/suppress that there's a warning.

素年丶 2024-10-14 14:13:14

您可以添加 @SuppressWarnings("unchecked") 注释。这不会更改方法签名,并允许您执行“不安全”的操作而不生成警告。您的代码确实安全,因此可以抑制警告。请注意,根据 @Affe 的回答,返回后可能会发生不好的事情,但您当然可以正确实现您的方法。

Java Collections 框架在内部执行此类操作,因此它不仅仅是一个 hack。嗯,它一个黑客,但它是一个不错的黑客。嗯,虽然不是那么好,但它确实有效。有点。

You can add an @SuppressWarnings("unchecked") annotation. This does not change the method signature and allows you to do "unsafe" things without generating a warning. Your code is genuinely safe, so it's OK to suppress the warning. Note that, per @Affe's answer, Bad Things may happen after you return, but you can certainly implement your method correctly.

The Java Collections framework does this kind of stuff internally so it's not just a hack. Well, it is a hack, but it's an OK hack. Well, it's not that OK, but it works. Kinda.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文