【问题标题】:using ArrayList for counting使用 ArrayList 进行计数
【发布时间】:2011-10-14 07:17:23
【问题描述】:

在我的以下代码中,我有 2 个计数器,所以我使用了 ArrayList ,因为我想在循环外获取每个计数项目的数量。 我使用 arrayList 如下,它在打印时给了我预期的值,但我想知道我是否可以使用 array [] 优化我的代码,集合而不是 list 以避免两次 list.add(cout1);list .add(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);

【问题讨论】:

  • 很不清楚你的意思。如果你知道你有两个计数器,并且你有两个变量,你为什么要将它们放入一个集合中? tables 是什么意思?
  • 是否有专供打印的计数器?
  • 我只想计算 string1 的数量 if(action1) 字符串的数量 if(action2) 所以我有 2 个计数器,我想知道是否有一种方法可以在不添加两次的情况下进行计数count1,count2 到列表中?

标签: java arraylist


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    用于产生arraylist: Arrays.asList(count1, count2)

    【讨论】:

    • 好的,所以在这里我必须删除: ArrayList list = new ArrayList(); ?
    【解决方案3】:

    你可以这样做

    int[] counter = new int[2];
    
          for (int i = 0; i < nb; i++)
          {
    
            if (action)
            {
              counter[0]++;
    
            }
            if (votherAction)
            {
              counter[1]++;
    
            }
    
          }
    

    但好处是微乎其微的

    【讨论】:

      【解决方案4】:

      您可以将它们添加到String,而无需使用ArrayList。 你可以用它来打印。

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

      编辑:您可以使用Array 代替ArrayList

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

      【讨论】:

      • 不,我不只是用来打印,我想在循环外使用我的 count1、count2 的值,并想知道是否有比我的更好的方法
      • 我必须在循环外使用计数器的内容
      • 你可以在外面使用countArr
      猜你喜欢
      • 2017-08-03
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      相关资源
      最近更新 更多