gpt4 book ai didi

java - Java 使用什么机制不允许将数组引用重新分配给另一个具有更大类型的引用?

转载 作者:行者123 更新时间:2023-12-03 23:07:39 24 4
gpt4 key购买 nike

我看过的一本书上说

int[] splats;
int[] dats = new int[4];
char[] letters = new char[5];
splats = dats; //ok
splats = letters; //not ok

不允许这样赋值的机制是什么?

编辑:

相对于这个赋值 where

int[] weightList = new int[5];
byte b = 4;
char c = 'c';
short s = 7;
weightList[0] = b; //ok
weightList[1] = c; //ok
weightList[2] = s; //ok

这是允许的。

编辑:
我想我明白扩大和缩小是如何工作的,但在我的脑海里

new int[4];
and
new char[4];

是堆中的两个数组对象,类型为'array'。不是吗?
也许喜欢

new List<int>
and
new List<char>

确定它们各自的元素类型不同,但 List 对象本身都是同一个List类型。
我读到对象数组被允许执行该操作只要分配端有一个更窄的类型(子类)。
所以也许我可以这样想

Because the primitive type char does not inherit the primitive type int, you cannot reassign an array of chars into an array of ints ?


当然,一种原始类型“扩展”另一种原始类型听起来不对,但只是使其更易于理解。

最佳答案

“机制”是类型安全。

  • char[] 的引用与对 int[] 的引用不是同一类型>
  • 他们之间没有继承关系
  • 没有指定的加宽转换规则

所以赋值是非法的。

关于java - Java 使用什么机制不允许将数组引用重新分配给另一个具有更大类型的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16536722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com