gpt4 book ai didi

java - 将 char 数组分配给 int 数组

转载 作者:行者123 更新时间:2023-11-29 09:42:11 27 4
gpt4 key购买 nike

谁能解释一下为什么下面代码中的最后一个赋值是无效的

类 ScjpTest 扩展了 BounceObject 实现了 Bouncable{

static int ac = 5;
static char ab = 'd';

static int[] a = new int[]{1,2,3};
static int[] b = new int[]{1,2,3};
static char[] c = new char[]{'a','b'};

public static void main(String[] args){
a = b;
b = a;

ac = ab; //This is accepted
a = c; //This is rejected
}

编译器报错如下

ScjpTest.java:10: incompatible types
found : char[]
required: int[]
a = c;
^
1 error

以下也被接受

class Animal{}
class Horse extends Animal{]

Animal[] animals = new Animal[2];
Horse[] horses = new Horses[2];

animals = horses;

为什么我不能将 char 数组分配给 int 数组?

最佳答案

因为语言规范禁止这样做。它在运行时将 String[] 视为 Object[],因为两者在内存中具有相同的表示形式。但是 char[] 和 int[] 具有不同的内存表示,如果对 int[] 的每个操作都必须检查它是否真的是伪装的 char[],那么速度将慢得令人无法接受。

引用类型的数组确实必须对赋值进行运行时检查,以便知道是否抛出 ArrayStoreException,但至少从它们中读取是独立于元素类型的。

关于java - 将 char 数组分配给 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6985295/

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