使用Arrays.deepToString()从多维数组中的特定索引打印

问题描述 投票:-1回答:3

有没有办法使用Arrays.deepToString()从多维数组中打印特定值?

例如,我想在多维数组中打印索引[1,1]处的值。

我希望这是有道理的。

public class App {

    public static void main(String[] args) {

        int[][] a = {
                {10,20,30,40,50},{10,20,30,40,50}
        };

        System.out.println(Arrays.deepToString(a));
        System.out.println(Arrays.deepToString(a[1][1]));
    }    
}
java multidimensional-array
3个回答
0
投票
System.out.println(a[1][1]);

打印:

20

0
投票

Arrays中的deepToString(Object [])返回Object Array的String表示。像:-

 int[][] a = {{10,20,30,40,50},{10,20,30,40,50}};

 System.out.println(Arrays.deepToString(a));

 Output:- [[10, 20, 30, 40, 50], [10, 20, 30, 40, 50]] // String representation of 'a'

deepToString()就是这个。

如果要打印特定元素则使用数组的坐标,如

System.out.println(a[1][2]);  //Output:-  30

0
投票

Short Answer

是的,它有效。您在帖子的评论中注意到了这一点。

Why it works

Arrays.deepToString似乎以递归方式扩展(并在每个元素上调用toString方法)传递的任何数组。您的情况是“不是数组,只打印参数”的特例。在您的示例中,第二次调用deepToString是不必要的。

© www.soinside.com 2019 - 2024. All rights reserved.