下面是代码A:
/*
* Created on 2005-3-21
*/
/**
* @author jtzhu
*/
import java.util.NoSuchElementException;
import java.util.Date;
public class list {
class Element
{
final int datum;
Element next;
Element(final int datum, Element next)
{
this.datum = datum;
this.next = next;
}
}
class Iter
{
Element curr;
Iter(Element head)
{
this.curr = head;
}
boolean hasNext()
{
return curr != null;
}
int next()
{
if(curr == null)
throw new NoSuchElementException();
final int result = curr.datum;
curr = curr.next;
return result;
}
};
Element head;
Element tail;
list()
{
head = tail = null;
}
boolean isEmpty()
{
return head == null;
}
void purge()
{
Element curr = head;
Element next;
while(curr!=null)
{
next = curr.next;
curr = next;
}
head = tail = null;
}
void append(final int datum)
{
if(head == null)
{
head = tail = new Element(datum,null);
}
else
{
tail.next = new Element(datum, null);
tail = tail.next;
}
}
void extract(final int datum)
{
if(isEmpty())
throw new NoSuchElementException();
Element curr = head;
Element pre = null;
while(curr != null && curr.datum != datum)
{
pre = curr;
curr = curr.next;
}
if(curr == null)
throw new NoSuchElementException();
if(curr == head)
{
Element next = head.next;
head = next;
}
else
{
pre.next = curr.next;
}
if(curr == tail)
tail = pre;
}
void assign(list another)
{
if(this == another)
return;
Iter iter = another.iterator();
purge();
while(iter.hasNext())
{
append(iter.next());
}
}
Iter iterator()
{
return new Iter(head);
}
public static void main(String[] args) {
list from = new list();
list to = new list();
final int length = 100000;
final int innerLoops = 100;
for(int i=0;i<length;i++)
from.append(i);
long start,end;
double timeuse;
for(int i=0;i<3;i++)
{
System.out.print("loop "+i+":\n");
System.gc();
timeuse = 0;
for(int k=0;k<innerLoops;k++)
{
to.purge();
start = (new Date()).getTime();
for(int j=0;j<length;j++)
to.append(j);
end = (new Date()).getTime();
timeuse+= (double)(end-start);
}
System.out.print("append: "+length/timeuse*innerLoops/1000+"M/s\t");
timeuse = 0;
for(int k=0;k<innerLoops;k++)
{
to.purge();
start = (new Date()).getTime();
to.assign(from);
end = (new Date()).getTime();
timeuse+=(double)(end-start);
}
System.out.print("assign: "+innerLoops/timeuse*1000+"/s\t");
start = (new Date()).getTime();
for(int j=length/2;j<(length/2+1000);j++)
to.extract(j);
end = (new Date()).getTime();
timeuse=(double)(end-start);
System.out.print("extract: "+1000/timeuse+"k/s\t");
timeuse = 0;
for(int k=0;k<innerLoops;k++)
{
to.assign(from);
start = (new Date()).getTime();
to.purge();
end = (new Date()).getTime();
timeuse+=(double)(end-start);
}
System.out.print("purge: "+innerLoops/timeuse*1000+"/s\n");
}
}
}
编译方式如下:
javac list.java
java list
本文地址:http://com.8s8s.com/it/it22753.htm