may i know how to exe follow java prog?
-- source code --
import java.util.Iterator;
import java.lang.reflect.Array;
public class ArrayIterator implements Iterator {
private final int size;
private int cursor;
private final Object array;
private ArrayIterator(Object array) {
this.array = array;
this.size = Array.getLength(array);
}
public static Iterator getInstance(Object obj) {
Class type = obj.getClass();
if (!type.isArray()) {
throw new IllegalArgumentException("Invalid type: " + type);
} else {
return new ArrayIterator(obj);
}
}
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return (cursor < size);
}
public Object next() {
return Array.get(array, cursor++);
}
public static void main(String args[]) {
loop(ArrayIterator.getInstance(args));
int intArray[] = {10, 20, 30, 40, 50};
loop(ArrayIterator.getInstance(intArray));
try {
loop(ArrayIterator.getInstance("Hello, World!"));
} catch (IllegalArgumentException e) {
System.err.println("Bad arg: " + e.getMessage());
}
}
private static void loop(Iterator iter) {
while (iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println("-------");
}
}
-- source code --
import java.util.Iterator;
import java.lang.reflect.Array;
public class ArrayIterator implements Iterator {
private final int size;
private int cursor;
private final Object array;
private ArrayIterator(Object array) {
this.array = array;
this.size = Array.getLength(array);
}
public static Iterator getInstance(Object obj) {
Class type = obj.getClass();
if (!type.isArray()) {
throw new IllegalArgumentException("Invalid type: " + type);
} else {
return new ArrayIterator(obj);
}
}
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return (cursor < size);
}
public Object next() {
return Array.get(array, cursor++);
}
public static void main(String args[]) {
loop(ArrayIterator.getInstance(args));
int intArray[] = {10, 20, 30, 40, 50};
loop(ArrayIterator.getInstance(intArray));
try {
loop(ArrayIterator.getInstance("Hello, World!"));
} catch (IllegalArgumentException e) {
System.err.println("Bad arg: " + e.getMessage());
}
}
private static void loop(Iterator iter) {
while (iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println("-------");
}
}