수요일, 5월 17, 2006

자바 Tiger의 System.nanoTime 추가 !!

나노초 단위의 체크가 가능한 System클래스내의 nanoTime메소드가 추가되었다
비로소 더 정확한 알고리즘의 수행속도 Check가 가능하다.

다음은 샘플이지만 결국 간단하게 사용할 수 밖에 없을 것이다.
static의 클래스레벨의 속성 때문에 여러군데에서 동시에 벤치마크를 수행할 수 없다.
하지만 간단한 수행시간 체크정도는 수행할 것이다.

package kr.ac.kyungnam.dblab;

public class Benchmark {
/**
* The field that has starting time
*/
private static long startTime = 0;

/**
* The field that has ending time
*/
private static long endTime = 0;

/**
* The method that set the starting time
*/
public static void start() {
//startTime = System.currentTimeMillis();
startTime = System.nanoTime();
}

/**
* The method that set the finishing time
*/
public static void finish() {
//endTime = System.currentTimeMillis();
endTime = System.nanoTime();
}

/**
* the difference between endtime and starttime
* @return
* return nano second time
*/
public static long result() {
return endTime - startTime;
}


}

목요일, 5월 11, 2006

Simple "Iterator Pattern" Example by Mjseo (외부 Iterator구현 클래스)

/*
* Aggregate인터페이스는
* 집합적연 요소를 가지는 클래스에
* iterator메소드를 구현하게 함으로서
* iterator를 제공하게 한다.
*/
interface Aggregate {
public Iterator iterator();
}
/*
* Iterator메소드는
* 집합적 요소 구성물의 현제 엘리먼트를 반환후 다음엘리먼트로 포인터 이동(next)과
* 그리고 다음엘리먼트를 가지는지의 여부(hasNext)를 가지는 메소드를 가진다.
* hasPrev 또는 moveToFirst 또는 moveToLast메소드를 추가할 수 있다.
*/
interface Iterator {
public Object next();
public boolean hasNext();
}
/*
* My list는 어떤 집합적 요소를 반환하는 샘플 클래스로
* 이는 내부 배열값을 가지고 이것을 반환할수 있는 함수
* 그리고 MyList의 크기를 반환하는 함수로 구성된다.
*/
class MyList implements Aggregate {
String[] r = { "abc", "cde" };

public String get(int index) {
return r[index];
}

public int getLength() {
return r.length;
}

public Iterator iterator() {
return new MyListIterator(this);
}
}
/*
* Iterator 인터페이스를 실제루 구현한 MyListIterator
* MyList의 메소드를 이용하여 집합적 요소를 탐색한다.
*/
class MyListIterator implements Iterator {
int index = 0;

MyList ml;

public MyListIterator(MyList ml) {
this.ml = ml;
}

public Object next() {
return ml.get(index++);
}

public boolean hasNext() {
if (index == ml.getLength())
return false;
else
return true;
}
}
/*
* 실제 사용을 보여주는 Example
*/
public class Test {
public static void main(String[] args) {
// MyList객체 선언
MyList m = new MyList();
// 이터레이터 생성
Iterator i = m.iterator();
// 다음 요소를 가지지 않으을때 까지 현재요소를 출력한다.
while (i.hasNext())
System.out.println(i.next());
}
}