You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Java中打印int数组会输出[I@2c7b84de?求解释

为什么打印int数组会输出[I@2c7b84de?

你看到的[I@2c7b84de是Java数组对象默认的toString()方法输出结果,原因如下:

  1. 默认调用Object的toString():所有Java类都继承自Object类,数组也不例外。当你直接用System.out.println(numeros)打印数组时,实际调用的是Object类的toString()方法,它的输出格式固定为:[类型标识@对象哈希码的十六进制值]。
  2. 拆解输出含义:
    • [:表示这是一个数组对象
    • I:是Java中int类型的缩写标识(其他类型比如D代表double,L代表引用类型)
    • @2c7b84de:@后面的字符串是该数组对象在内存中的哈希码的十六进制表示,用来区分不同的对象实例。

怎么正确打印数组内容?

如果你想输出数组里的具体元素,有几种常用方法:

方法1:使用Arrays.toString()

这是最简便的方式,需要导入java.util.Arrays包,修改代码如下:

import java.util.Arrays;

public class EJer22 {
    public static void main(String[] args){
        int[] numeros = { 50, 21, 6, 97, 18 };
        System.out.println(Arrays.toString(numeros)); // 输出 [50, 21, 6, 97, 18]
    }

    public static int[] pruebas (int[] P){
        int[] S = new int[P.length];
        if(P.length < 10){
            System.out.println("Hay mas de 10 numeros");
        } else {
            for(int i = 0; i < P.length; i++){
                if(10 >= P[i]){
                    S[i] = -1;
                }else{
                    S[i] = P[i];
                }
            }
        }
        return S;
    }
}

方法2:手动循环遍历数组

自己写循环逐个打印元素,灵活度更高:

public class EJer22 {
    public static void main(String[] args){
        int[] numeros = { 50, 21, 6, 97, 18 };
        // 手动遍历打印
        System.out.print("[");
        for(int i = 0; i < numeros.length; i++){
            System.out.print(numeros[i]);
            if(i != numeros.length - 1){
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }

    // 其余代码不变
    public static int[] pruebas (int[] P){
        int[] S = new int[P.length];
        if(P.length < 10){
            System.out.println("Hay mas de 10 numeros");
        } else {
            for(int i = 0; i < P.length; i++){
                if(10 >= P[i]){
                    S[i] = -1;
                }else{
                    S[i] = P[i];
                }
            }
        }
        return S;
    }
}

方法3:针对多维数组用Arrays.deepToString()

如果是嵌套的多维数组,用Arrays.deepToString()可以递归打印所有层级的元素。

内容的提问来源于stack exchange,提问作者Rai1233

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:50:25