Which of these is more efficient? :
ArrayList<Integer> list = new ArrayList<Integer>();
for(int a : list){
log.i(tag, a + "");
}
SparseIntArray list2 = new SparseIntArray();
int count = list2.size();
for(int j = 0; j < count; j++) {
log.i(tag, list2.get(j) + "");
}
Or, is there a faster way to read the contents of the list?
Efficiency, in this case, is irrelevant, since those two do completely different things.
I think you realize that your
ArrayListexample iterates through all the elements of the array-list.What you don’t realize is that your
SparseIntArrayexample does not iterate through all the elements of the sparse-integer-array, because the keys of a sparse-integer-array do not range from zero to array-size-minus-one. Rather, its keys are arbitrary integers. A sparse-integer-array has as much in common, interface-wise, withHashMap<Integer, Integer>as withArrayList<Integer>.(This, by the way, relates to a general rule of software design: it is better for your code to be correct than efficient. You can always take correct, clean code and find ways to improve its performance; but it’s very hard to take fast, buggy code and find ways to make it correct.)