0

on my following code, I have 2 counters so I used an ArrayList , as I want to get number of each counted items outside loop. I've used arrayList as follow which gives me the expected values at print, but I would like to know if I can optimize my code using array [] , collections instead of list to avoid to to twice 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);
3
  • 3
    It is very unclear what you mean. If you know you have two counters, and you have two variables for them, why do you want to put them into a collection? And what do you mean by tables? Commented Oct 14, 2011 at 7:19
  • Are there counters for printing purpose only? Commented Oct 14, 2011 at 7:25
  • I just want to count number of string1 if(action1) number of strings2 if(action2) so I have 2 counters , and I would like to know if there a a way to make the cound without adding twice count1,count2 to the list? Commented Oct 14, 2011 at 7:26

4 Answers 4

2

You can use FluentUtils.pair() instead of ArrayList (http://code.google.com/p/fluentutils/) like return pair(counter1, counter2)

Sign up to request clarification or add additional context in comments.

Comments

0

Use to produce arraylist: Arrays.asList(count1, count2)

1 Comment

ok, so here I have to remove : ArrayList<Integer> list = new ArrayList<Integer>(); ?
0

you can do that

int[] counter = new int[2];

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

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

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

        }

      }

but the benefice is minimal

Comments

0

You can just add them to a String and need not to use ArrayList. You can use this to print.

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

Edit: You can use Array instead of ArrayList.

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

3 Comments

no, I didn't use only to print , I would like to use values of my count1, count2 outside the loop and would like to know if there is a better way then mine to do it
I have to use the content of counters outside loop
You can use countArr outside.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.