java算法:抽象数据类型ADT
开发有关系数据和处理这些数据的方法的抽象数据模型是用计算机解决问题的过程中必不可少的步骤。
使用抽象数据类型,可以很好的把任何具体的数据结构表示与算法分开,利于研究算法。
抽象数据类型是一种智能通过接口访问的数据类型(值与值上的操作所构成的集合),我们把使用ADT的程序称为客户程序,把指定数据类型的程序称为实现。
抽象数据类型与其他数据类型的主要区别是:对于抽象数据类型,客户程序只能通过接口中提供的操作来访问数据值。接口把所有的数据表示和操作方法的实现完全与客户程序隔离。在Java中,一般不能直接访问数据,而是通过方法访问的。
例1:点的类实现
Java代码
publicclassPoint{
privatedoublex,y;
Point(){
x = Math.random();
y = Math.random();
}
Point(doublex,doubley){
this.x = x;
this.y = y;
}
doublex(){
returnx;
}
doubley(){
returny;
}
doubler(){
returnMath.sqrt(x * x + y * y);
}
doubletheta(){
returnMath.atan2(y , x);
}
doubledistance(Point p){
doubledx = x - p.x;
doubledy = y - p.y;
returnMath.sqrt(dx * dx + dy * dy);
}
publicString toString(){
return"("+ x +" , "+ y +")";
}
}
public class Point{
private double x,y;
Point(){
x = Math.random();
y = Math.random();
}
Point(double x, double y){
this.x = x;
this.y = y;
}
double x(){
return x;
}
double y(){
return y;
}
double r(){
return Math.sqrt(x * x + y * y);
}
double theta(){
return Math.atan2(y , x);
}
double distance(Point p){
double dx = x - p.x;
double dy = y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
public String toString(){
return "(" + x + " , " + y + ")";
}
}
定义ADT的根本原因:通过使客户不能直接访问数据表示,可以随意地对数据表示进行修改!在这种情况下,使用极坐标来表示点,但客户程序可以不管点是如何实现的而执行相同的运算。
例2:点类(替换实现)
Java代码
publicclassPoint2{
privatedoubler,theta;
privatestaticPoint2 p2;
publicstaticPoint2 getInstance(){
doublex = Math.random() *100;
doubley = Math.random() *100;
p2 =newPoint2(x,y);
returnp2;
}
publicPoint2(doublex,doubley){
this.r = Math.sqrt(x * x + y * y);
this.theta = Math.atan2(y , x);
}
publicdoublex(){
returnr * Math.cos(theta);
}
publicdoubley(){
returnr * Math.sin(theta);
}
publicdoubler(){
returnr;
}
publicdoubletheta(){
returntheta;
}
publicdoubledistance(Point2 p){
doubledx = x() - p.x();
doubledy = y() - p.y();
returnMath.sqrt(dx * dx + dy * dy);
}
publicString toString(){
return"("+ x() +" , "+ y() +")";
}
}
public class Point2{
private double r,theta;
private static Point2 p2;
public static Point2 getInstance(){
double x = Math.random() * 100;
double y = Math.random() * 100;
p2 = new Point2(x,y);
return p2;
}
public Point2(double x, double y){
this.r = Math.sqrt(x * x + y * y);
this.theta = Math.atan2(y , x);
}
public double x(){
return r * Math.cos(theta);
}
public double y(){
return r * Math.sin(theta);
}
public double r(){
return r;
}
public double theta(){
return theta;
}
public double distance(Point2 p){
double dx = x() - p.x();
double dy = y() - p.y();
return Math.sqrt(dx * dx + dy * dy);
}
public String toString(){
return "(" + x() + " , " + y() + ")";
}
}
使用ADT,精确提供返回客户感兴趣的数据方法。而且在实现方法更灵活。
例3:点的ADT接口
Java代码
publicinterfaceIPoint {
doublex();
doubley();
doubler();
doubletheta();
doubledistance(Point p);
publicString toString();
}
public interface IPoint {
double x();
double y();
double r();
double theta();
double distance(Point p);
public String toString();
}
ADT是作为支持模块化编程的一种有效机制。模块化编程是现代大型软件系统的一种组织方法。ADT提供了灵活的修改,ADT接口明确定义了程序访问的方法。