Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I'm iterating over two arrays at once, which one do I use as the limit?

I'm always struggling with something like the following Java example:

String breads[] = {"Brown", "White", "Sandwich"};
int count[] = new int[breads.length];
for (int i = 0; i < ****; i++)
{
   // Prompt the number of breads
}

****: which array.length should I choose?
I can choose between breads.length and count.length
I know it would be the same result, but I don't know which one I shoud choose.

There are many other examples where I get the same problem.
I'm sure that you have encountered this problem as well in the past.

What should you choose? Are there general agreements?

Thanks

like image 917
Martijn Courteaux Avatar asked Mar 08 '10 19:03

Martijn Courteaux


1 Answers

I think I understand your question.

The answer is don't use arrays.

In this case use a map of:

Map<String, Integer> breadCount = new TreeMap<String, Integer>();

breadCount.put("Brown", 0);
breadCount.put("White", 0);
breadCount.put("Sandwich", 0);

Then there's only one "length", which is breadCount.size()

Example is in Java

like image 165
Pyrolistical Avatar answered Sep 27 '22 18:09

Pyrolistical