python小菜 2009-01-03 20:39 采纳率: 0%
浏览 1227
已采纳

打印 Java 数组最简单的方法是什么?

In Java, arrays don't override toString(), so if you try to print one directly, you get the className + @ + the hex of the hashCode of the array, as defined by Object.toString():

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray);     // prints something like '[I@3343c8b3'

But usually we'd actually want something more like [1, 2, 3, 4, 5]. What's the simplest way of doing that? Here are some example inputs and outputs:

// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]

转载于:https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array

  • 写回答

29条回答 默认 最新

  • elliott.david 2012-10-03 08:51
    关注

    Since Java 5 you can use Arrays.toString(arr) for simple arrays or Arrays.deepToString(arr) for nested arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

    Examples:

    Simple Array:

    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));
    

    Output:

    [John, Mary, Bob]
    

    Nested Array:

    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    System.out.println(Arrays.toString(deepArray));
    //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    System.out.println(Arrays.deepToString(deepArray));
    

    Output:

    [[John, Mary], [Alice, Bob]]
    

    double Array:

    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));
    

    Output:

    [7.0, 9.0, 5.0, 1.0, 3.0 ]
    

    int Array:

    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));
    

    Output:

    [7, 9, 5, 1, 3 ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services