繁体   English   中英

如何更改列表Java列表中的元素

[英]How to change an element in a list of lists Java

这是我的代码的精妙之处,我正在制作一个5x5的网格,并为每个部分设置了随机的颜色。 我需要将列表中指定的y_loc和x_loc设置为随机选择的颜色,除非我无法找到方法。 它应该是第二行,而不是像id那样运行。 我知道我可以用更长的代码来做到这一点,但是用更少的代码来做会很好。

//making the map
    ArrayList<ArrayList<String>> fullmap = new ArrayList<ArrayList<String>>();
    ArrayList<String> y_row_0 = new ArrayList<String>();
    ArrayList<String> y_row_1 = new ArrayList<String>();
    ArrayList<String> y_row_2 = new ArrayList<String>();
    ArrayList<String> y_row_3 = new ArrayList<String>();
    ArrayList<String> y_row_4 = new ArrayList<String>();
//adding each row
    fullmap.add(y_row_0);
    fullmap.add(y_row_1);
    fullmap.add(y_row_2);
    fullmap.add(y_row_3);
    fullmap.add(y_row_4);
    Random rn = new Random();
    //loop to randomly pick colors then set them to their destined locations
    for (int y_loc = 0; y_loc < 6; y_loc++){
        for (int x_loc = 0; x_loc < 6; x_loc++){
            colorPicked = false;
            while (!colorPicked){
                int ranNum = rn.nextInt();
                if (ranNum ==0){
                    if (redTot < 5) {
                        redTot += 1;
                        fullmap.set(y_loc).set(x_loc, "Red"));
                        colorPicked = true;

您应该具有以下内容:

fullmap.get(y_loc).set(x_loc, "Red"));

注意“获取”。 您在y位置“获取”列表,该列表返回一个数组列表,然后对该数组列表调用“ set”以在“ x_loc”值的索引中设置实际值。

由于您的列表中有列表,因此要在特定位置设置某些内容,您必须get内部列表,然后对其进行set 以下应该工作:

fullmap.get(y_loc).set(x_loc, "Red"));

另外,由于您似乎总是有5x5的矩阵,因此建议您使用双精度数组。 那将成为这一行:

fullmap[x_loc][y_loc] = "Red";

您需要进行一些更改:

  • 在声明子列表时,您需要确保它们具有5个空/空元素。 否则set将抛出IndexOutOfBoundsException 例如,您需要这样声明列表:

    ArrayList<String> y_row_0 = Arrays.asList(new String[5]);//Assuming it will have 5 elements

  • 设置元素时,首先需要get相应的子列表,例如,以下内容需要更改:

    fullmap.set(y_loc).set(x_loc, "Red"));

    fullmap.get(y_loc).set(x_loc, "Red"));

其他人已经讨论了索引问题。 除此之外,我相信您的条件可能未按预期执行。 nextInt()将返回一个合理的统一随机数,范围为-2147483648至2147483647。您有1/2 ^ 64的机会得到0 将随机数范围减小到更合理的范围。 例如, nextInt(10)将返回0到9之间的一个随机数。

此外,如果概率太低,您将不会一直获得5次红色。 为了保证5个选择并出于计算效率的考虑,最好随机选择数组索引并评估是否设置了颜色,例如以下伪代码

    int redTot = 0;
    while ( redTot < 5 ) {
        int r = rn.nextInt( 5 );
        int c = rn.nextInt( 5 );
        String color = fullmap.get( r ).get( c );
        if ( color == null ) {
            fullmap.get( r ).set( c, "Red" );
            redTot++;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM