Reputation: 29
for (int i = 0; i < numArray.size(); i++) {
if (numArray.get(i) % 2 == 0) {
evenSum += numArray.get(i);
outputArea.append(numArray.get(i) + "\n");
}
}
Is there any way to get the line
if (numArray.get(i) % 2 == 0) {
in the for loop condition line? And if so, would that be more efficient than how it is right now?
Upvotes: 0
Views: 70
Reputation: 2897
You could put the condition in the for loop:
for (int i = 0; (i < numArray.size()) && (numArray.get(i) % 2 == 0); i++) {
evenSum += numArray.get(i);
outputArea.append(numArray.get(i) + "\n");
}
However, it will change what the loop is doing, because it will stop as soon as it hits an odd number. That may or may not be what you want, but is definitely different than the original code, which continues through the whole array.
If you do want to iterate over the whole array, it's probably best to use the foreach version of iteration, and let the compiler produce the fastest code:
for (int num : numArray) {
if (num % 2 == 0) {
evenSum += num;
outputArea.append(num).append("\n");
}
}
Upvotes: 2
Reputation: 1186
I presume you are summing even numbers in the ArrayList, you asked for more efficiency so here you go, instead of using .get() we will use iterator as it will speed things up and we will use another faster method for checking if number is even:
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) throws InterruptedException {
int sum = 0;
List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
Iterator<Integer> iter = numbers.iterator();
int num;
while(iter.hasNext()){
if (((num = iter.next()) & 1) == 0) // number is even
sum += num;
}
System.out.println("Sum of all even numbers is: " + sum);
}
}
If you had a really big list it would speed things up quite a bit compared to the original code.
EDIT:
Here are resources that you can study:
http://www.javainterviewpoint.com/check-number-even-odd-modulo-division-operators-java/
Upvotes: 0