I am declaring a String array as:
String[] items = new String[10];
items[0] = "item1";
items[1] = "item2";
How can I find length of items in an efficient way that it contains only 2 elements. items.length returns 10.
I am running a loop already which runs to its length. I want to so something with this code without adding new code/loop to count number of not-null elements. What can I replace with items.length
for (int i = 0; i < items.length; i++) {
...
}
No. You will need to loop and see how many non-
nullelements there are.Consider using e.g. an
ArrayList<String>instead of a raw array.UPDATE
To answer the new part of your question, your loop can become: