|
编写自己的工具类
因为手机内存和功能的限制,J2ME只提供了部分的J2SE工具类供使用者调用。所以有时我们不得不编写自己的工具类来实现一些特殊的功能。下面给出的kSet类就类似于J2SE中Set工具类的功能。它用来记录游戏中被删去的方块集合,同时保证集合中没有相同元素。
/**
* Description: Set类在J2ME上的实现
*Date:2003.2.28
*Author:TomJava
*email:tomjava@sohu.com
*/
public class kSet
{//用单链表实现
private kSetNode head;
public kSet()
{
head=null;
}
//将kSet清空
public void clear()
{
head=null;
}
//向kSet中添加元素
public boolean add(int x,int y)
{
kSetNode node=new kSetNode(x,y);
return add(node);
}
//向kSet中添加元素
public boolean add(kSetNode node)
{
if(!contains(node))
{
node.next=head;
head=node;
return true;
}else
{
return false;
}
}
//判断kSet是否为空
public boolean isEmpty()
{
if(head==null)
return true;
else
return false;
}
//摘下链表头元素并返回此元素
public kSetNode getFirst()
{
kSetNode p=head;
head=p.next;
return p;
}
//遍历kSet,如果有相同元素返回true,否则返回false
public boolean contains(kSetNode node)
{
kSetNode p = head;
while (p != null) {
if(p.equals(node))return true;
p=p.next;
}
return false;
}
}
//kSet中的元素
public class kSetNode
{
public int x,y;
public kSetNode next;
public kSetNode(int x,int y)
{
this.x=x;
this.y=y;
next=null;
}
public boolean equals(kSetNode node)
{
if(node.x==x&&node.y==y)
return true;
else
return false;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
|
kSetNode类负责记录被删除方块的坐标,它重载equals()方法用来判断两个方块是否是同一个方块。kSet类是由kSetNode对象组成的没有相同元素的集合,用单链表实现,并且提供了 getFirst()、add()、clear()、isEmpty()、contains()等方法供其它类调用。编写和使用一些这样的工具类,将大大加快编程的速度,也使程序变得更加清晰。
|