Java 使用ArrayList进行计数

Java 使用ArrayList进行计数,java,arraylist,Java,Arraylist,在下面的代码中,我有2个计数器,所以我使用了一个ArrayList,因为我想得到循环外每个计数项的数量。 我使用了arrayList,如下所示,它在打印时为我提供了预期值,但我想知道是否可以使用array[],collections而不是list来优化我的代码,以避免重复使用list.add(cout1);列表。添加(count2) ArrayList list=new ArrayList(); int count1=0; int count2=0; 对于(int i=0;i

在下面的代码中,我有2个计数器,所以我使用了一个ArrayList,因为我想得到循环外每个计数项的数量。 我使用了arrayList,如下所示,它在打印时为我提供了预期值,但我想知道是否可以使用array[],collections而不是list来优化我的代码,以避免重复使用list.add(cout1);列表。添加(count2)

ArrayList list=new ArrayList();
int count1=0;
int count2=0;
对于(int i=0;i
用于生成arraylist:
Arrays.asList(count1,count2)

您只需将它们添加到
字符串中
,无需使用
ArrayList
。 你可以用这个来打印

String counterStr = "Count 1 : " + count1 + ", Count 2 : " + count2;
编辑:您可以使用
Array
而不是
ArrayList

int[] countArr = new int[2];
...
countArr[0] = counter1;
countArr[1] = counter2;
你能做到的

int[] counter = new int[2];

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

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

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

        }

      }
int[]计数器=新的int[2];
对于(int i=0;i

但是收益是最小的

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

你的意思很不清楚。如果您知道有两个计数器,并且有两个变量,那么为什么要将它们放入集合中?你所说的表是什么意思?有只用于打印的计数器吗?我只想数一数string1 if(action1)的数量strings2 if(action2)所以我有两个计数器,我想知道是否有一种方法可以在列表中不添加两次count1,count2的情况下创建一个计数器?不,我只用于打印,我想在循环外使用我的count1、count2的值,并且想知道是否有比我更好的方法来实现它。我必须使用循环外计数器的内容。你可以使用
countArr
outside.ok,所以我必须删除:ArrayList list=new ArrayList()?
int[] counter = new int[2];

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

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

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

        }

      }