为什么Java不允许扩展数组类型

为什么Java不允许扩展数组类型

本文介绍了为什么Java不允许扩展数组类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一项实验,我尝试扩展 int -array,如下所示:

As an experiment, I tried to extend an int-array like this:

public class IntArrayExtension extends int[]{
 // additional fields and methods.
}

添加一些与排序,交换,子阵列构建等相关的方法。在课堂上。但是我在编译时遇到了这个错误:

to add some methods related to sorting, swapping, sub-array building etc. in the class itself. But I got this error while compiling:

IntArrayExtension.java:1: unexpected type
found   : int[]
required: class
public class IntArrayExtension extends int[]{
                                          ^
1 error

我很想知道:为什么Java不允许扩展数组?

I am curious to know: why Java does not allow to extend an array?

推荐答案

扩展一个基本类型,如 String 或一个数组会打开安全漏洞。如果Java允许您扩展数组,那么采用数组的方法将变得不安全。这就是字符串 final 的原因,并且根本无法扩展数组。

Extending a fundamental type such as a String or an array opens up security holes. If Java let you extend an array, its methods that take arrays would become insecure. That is why strings are final, and arrays cannot be extended at all.

例如,您可以覆盖 clone()方法,并返回不正确大小的数组。这有可能破坏以数组作为参数的系统代码的逻辑。

For example, you could override the clone() method, and return an array of incorrect size. This has a potential of breaking the logic of system code that takes an array as its parameter.

除此之外,数组是Java中的特殊对象,因为它们是没有类定义。

On top of that, arrays are special objects in Java, in that they do not have a class definition.

您尝试解决的问题有两种解决方案:

There are two solution to the problem that you are trying to solve:


  • 您可以使用静态方法将逻辑放入辅助类中,类似于集合等,或者

  • 您可以在 IntArrayExtension 类中封装数组,并提供用于访问数组及其附加功能的包装方法。

  • You could put the logic into a helper class with static methods, similar to Collections, etc. or
  • You could encapsulate an array inside your IntArrayExtension class, and provide wrapper methods for accessing the array and its additional features.

这篇关于为什么Java不允许扩展数组类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:32