This article is to explain why we need inner class in Java. Then give a very simple example for this purpose with live code.
In java, we typically define one class per file. But java also supports inner class functionality which we don't use it very frequently at the entry-level programming. As we deeply dive into more complicated java framework, we will find inner class is pretty useful and handy.
First, I would like to show a pretty simple data structure--a collection that can store any type of comparable object.
import java.util.Iterator;
public class OrderedCollection<E extends Comparable<? super E>> {
public Iterator<E> iterator() {
return this.new OrderedCollectionIterator();
}
/**
* the maximum size of the element array
*/
private final static int MAX = 1000;
private int currentPoint = -1;
private Object[] objects;
public OrderedCollection() {
objects = new Object[MAX];
}
public boolean isEmpty() {
return currentPoint == -1;
}
public void makeEmpty() {
for (int i = 0; i <= currentPoint; i++) {
objects[i]=null;
}
currentPoint = -1;
}
public void insert(E obj) {
currentPoint++;
objects[currentPoint] = obj;
}
public void remove(E e) {
boolean flag = false;
for (int i = 0; i <= currentPoint; i++) {
if (e.equals(objects[i])) {
flag = true;
continue;
}
// move the later elements forward to replace the removed element value
// set the duplicated element to null
if (flag) {
objects[i - 1] = objects[i];
objects[i] = null;
}
}
// set the pointer minus one
if (flag)
currentPoint--;
}
public boolean isPresent(E e) {
for (int i = 0; i <= currentPoint; i++) {
if (e.equals(objects[i])) {
return true;
}
}
return false;
}
public int size() {
return (currentPoint + 1);
}
public E findMax() {
if (isEmpty())
return null;
@SuppressWarnings("unchecked")
E max = (E) objects[0];
for (int i = 0; i <= currentPoint; i++) {
@SuppressWarnings("unchecked")
E ele = (E) objects[i];
if (ele.compareTo(max) > 0) {
max = ele;
}
}
return max;
}
}
Then I want this data structure implementing a Iterable interface. That means this data structure should have an iterator() method which return an iterator object.
With the mentioned iterator object, we can visit each element within this object using hasNext(), next() method.
private class OrderedCollectionIterator implements Iterator<E> {
int index = -1;
boolean isDeleteFlag = false;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return (index + 1) <= currentPoint;
}
@SuppressWarnings("unchecked")
@Override
public E next() {
// TODO Auto-generated method stub
index++;
isDeleteFlag = false;
return (E) objects[index];
}
/**
* delete the last element returned in the iteration
*/
@SuppressWarnings("unchecked")
@Override
public void remove() {
// TODO Auto-generated method stub
if (isDeleteFlag == false) {
OrderedCollection.this.remove((E) objects[index]);
}
isDeleteFlag = true;
}
}
No comments:
Post a Comment