Created
October 4, 2016 04:22
-
-
Save jjlumagbas/18f49196935f35081d1d9ba3220fa024 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class IteratorTest { | |
| public static void main(String[] args) { | |
| Collection<Integer> l = new LinkedList<Integer>(); | |
| l.add(1); | |
| l.add(2); | |
| l.add(5); | |
| System.out.println(average(l)); | |
| System.out.println(countInRange(l, 0, 3)); | |
| } | |
| public static float average(Collection<Integer> l) { | |
| int sum = 0; | |
| /* | |
| for (int i = 0; i < l.size(); i++) { | |
| sum += (Integer) l.get(i); | |
| } | |
| */ | |
| /* | |
| Iterator it = l.iterator(); | |
| while (it.hasNext()) { | |
| sum += (Integer) it.next(); | |
| } | |
| */ | |
| for (Integer i : l) { | |
| sum += i; | |
| } | |
| return sum / l.size(); | |
| } | |
| public static int countInRange(Collection<Integer> l, int lo, int hi) { | |
| int count = 0; | |
| Iterator it = l.iterator(); | |
| while (it.hasNext()) { | |
| int curr = (Integer) it.next(); | |
| count += (lo <= curr && curr <= hi) ? 1 : 0; | |
| } | |
| /* | |
| for (int i = 0; i < l.size(); i++) { | |
| int curr = (Integer) l.get(i); | |
| if (lo <= curr && curr <= hi) { | |
| count++; | |
| } | |
| } | |
| */ | |
| return count; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment