使用ArrayList进行计数

时间:2011-10-14 07:17:24

标签: java arraylist

在我的下面的代码中,我有2个计数器所以我使用了一个ArrayList,因为我想得到循环外每个计数项的数量。 我已经使用了arrayList,如下所示,它给出了print的预期值,但我想知道我是否可以使用array [],collection而不是list来优化我的代码,以避免两次list.add(cout1); list 。新增(COUNT2)?

ArrayList<Integer> list = new ArrayList<Integer>();
      int count1 = 0;
      int count2 = 0;

      for (int i = 0; i < nb; i++)
      {

        if (action)
        {
          counter1++;

        }
        if (votherAction)
        {
          counter2++;

        }

      }
    list.add(count1);
    list.add(count2);

4 个答案:

答案 0 :(得分:2)

您可以使用FluentUtils.pair()代替ArrayList(http://code.google.com/p/fluentutils/) 像返回对(counter1,counter2)

答案 1 :(得分:0)

用于制作arraylist:     Arrays.asList(count1,count2)

答案 2 :(得分:0)

您只需将其添加到String即可,无需使用ArrayList。 您可以使用它来打印。

String counterStr = "Count 1 : " + count1 + ", Count 2 : " + count2;

修改:您可以使用Array代替ArrayList

int[] countArr = new int[2];
...
countArr[0] = counter1;
countArr[1] = counter2;

答案 3 :(得分:0)

你可以那样做

int[] counter = new int[2];

      for (int i = 0; i < nb; i++)
      {

        if (action)
        {
          counter[0]++;

        }
        if (votherAction)
        {
          counter[1]++;

        }

      }

但是收益很少