简体   繁体   English

ArrayList 不添加元素

[英]ArrayList not adding elements

My array list is supposed to have a line of asterisk before and after each occurrence of the smallest number in it.我的数组列表应该在每次出现最小数字之前和之后都有一行星号。 I have debugged and all variables are holding the correct values but for some reason it wont add the values.我已经调试过并且所有变量都保存了正确的值,但由于某种原因它不会添加这些值。

Here is my code:这是我的代码:

int smallest = array[0];

        for (int i = 0; i < size; i++) 
            if (array[i] < smallest) 
                smallest = array[i];

                String smallestString = String.valueOf(smallest);

        ArrayList<String> list = new ArrayList<String>();

        for(int i = 0;i < size; i++)
            list.add(Integer.toString(array[i]));


        for (int i = 0; i < list.size(); i++)
        if (smallestString.equals(list.get(i))) {
            list.add(i, "*****"); 
            list.add(i + 2, "*****");
        }

            System.out.println("\n" + list);

            return smallest;

I think it is better to construct list as you go.我认为最好在进行时构建list Your way of inserting a new element to list (which is an ArrayList implementation) has two problems:您将新元素插入list (这是一个ArrayList实现)的方法有两个问题:

  1. The library is forced to shift everything by one -- this is slow图书馆被迫将所有内容都移一个——这很慢
  2. In general changing a list while iterating it is error prone.通常,在迭代时更改列表很容易出错。

I would rewrite the code as follows:我将代码重写如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListInsert {

    public static void main(String[] args) {
        Integer[] array = new Integer[]{1, 5, 2, 6, 7};

        int smallest = array[0];

        for (int i = 0; i < array.length; i++) 
            if (array[i] < smallest) 
                smallest = array[i];

        String smallestString = String.valueOf(smallest);

        List<String> list = new ArrayList<String>();

        for(int i = 0; i < array.length; i++) {
            if (smallestString.equals(String.valueOf(array[i]))) { // be careful!
                list.add("*****"); 
                list.add(Integer.toString(array[i]));
                list.add("*****");
            } else {
                list.add(Integer.toString(array[i]));
            }
        }

        System.out.println("array is\n" + Arrays.deepToString(array));
        System.out.println("list is\n" + list);

//            return smallest;

    }

}

The output would be:输出将是:

array is 
[1, 5, 2, 6, 7]
list is
[*****, 1, *****, 5, 2, 6, 7]

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

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