April 16, 2016
Java String Array Iterator Example
Problem
Given the signature of the Java method below
1 |
public static Iterator iterateStrings(String... strings) |
Provide implementation that iterates through each string in the order that they are provided but it skips null values
Solution
We implement the Iterable interface. We add a class member variable to store the list values in an array of strings. We override hasNext, next and remove methods. hasNext method keeps track of the current position in list as we iterate. next method was modified such that null values are skipped. remove method is kept intact. Here is the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
public static class MyClass implements Iterable { //Array of strings private String[] m_arr; //Constructor public MyClass(String[] arr) { this.m_arr = arr; } @Override public Iterator iterator() { Iterator it = new Iterator() { //Keep track of current position private int indx = 0; @Override //True as long as there are more elements public boolean hasNext() { return indx < m_arr.length; } @Override //Get next value but skip null values public String next() { //No more values to get if (!hasNext()) return null; //Get none null value if (m_arr[indx++] != null) { return m_arr[indx-1]; } //Skip null values else { return next(); } } @Override public void remove() { //do nothing } }; return it; } } public static Iterator iterateStrings(String... strings) { //Wrap the string array in our custom built list MyClass list = new MyClass(strings); return list.iterator(); } |