如何在Java中自动填充数组? [英] How to autofill an array in java..?

查看:63
本文介绍了如何在Java中自动填充数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用任何循环的情况下用'-1'自动填充Java中的数组(特别是多维数组)??

How can i autofill an array (specially multidimensional) in java with '-1' without using any loops..?

我知道默认情况下,java用'0'初始化数组的所有元素.但是,如果我想一次将所有零替换为-1怎么办..!不使用任何循环.

I know by default java initialize all the elements of array with '0'. But what if i want to replace all zeroes with -1 at once..! Without using any loop.

是否有任何可用的快捷方式??

Is there any shortcut available..?

推荐答案

您可以使用

You can use Arrays.fill to fill a one dimensional array but you'll have to loop for multi-dimensional arrays.

    int[][] array = new int[100][100];
    for (int[]a : array) {
        Arrays.fill(a, -1);
    }

您避免循环的原因是什么?如果您担心性能(并且确定存在问题),则可以执行经常执行的操作,这会将您的数组变成一维数组:

What's your reason to avoid loops ? If you're concerned with performances (and you're sure there is a problem) you might do what is often done, that is flatten your array in a one-dimensional one :

 int[] flatarray = new int[width*height];

然后,您只能用一个 fill (尽管它隐藏了一个循环)来填充它,而许多操作会更有效率.访问单元格应该是 flatarray [x + y * width] .但是您应该先进行概要分析,以确保需要此内容.

then you can fill it with only one fill (which hides a loop, though) and many manipulations would be a little more efficient. Accessing a cell would be flatarray[x+y*width].But you should profile first to ensure you need this.

这篇关于如何在Java中自动填充数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆