将所有计算过中点的边存入hashmap中 后续的每条边计算中点先到hashmap当中查询是否存-在存在就不用计算了 直接获取之前算过的中点 边类:两个端点 中点 重写equals方法用两个端点做比较不论方向- hashcode方法也要重写 计算hash值根据端点计算 K-V边 对象-K 中点-V package lbx628 ; import javax. swing. * ; import java. awt. * ; import java. util. HashMap ; import java. util. Objects ; import java. util. Random ; public class Drawmid extends JFrame { // 边类:两个端点,用于HashMap的Key public class Edge { Point p1, p2; //构造 public Edge ( Point p1, Point p2) { this . p1= p1; this . p2= p2; } public boolean equals ( Object o) { //判断地址是否相同,如果地址相同的话,那就相同 //this表示调动equals方法的对象 if ( this == o) { return true ; } // getClass()获取一个类的字节码对象,注:同一个类的字节码对象是相等的 // ||有true则true,具备短路作用,左边为true右边不执行 // o == null,对象为null,提高代码的健壮性 if ( o== null || /*省略了this.*/ getClass ( ) != o. getClass ( ) ) { return false ; } // 强制类型转换,o 强制转换成 e,目的是为了调用子类特有的成员 //e:o Edge e= ( Edge ) o; return ( p1. equals ( e. p1) && p2. equals ( e. p2) ) || ( p1. equals ( e. p2) && p2. equals ( e. p1) ) ; } public int hashCode ( ) { Point a, b; if ( p1. x< p2. x|| ( p1. x== p2. x&& p1. y< p2. y) ) { a= p1; b= p2; } else { a= p2; b= p1; } return Objects . hash ( a, b) ; } } Random random= new Random ( ) ; HashMap < Edge , Point > hm= new HashMap < > ( ) ; // 边→中点 缓存 public Drawmid ( ) { setTitle ( "谢尔宾斯基三角形递归" ) ; setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; setSize ( 800 , 800 ) ; setLocationRelativeTo ( null ) ; setVisible ( true ) ; } @Override public void paint ( Graphics g) { super . paint ( g) ; drawmidRect ( g, 400 , 50 , 150 , 650 , 700 , 650 , 100 , 150 ) ; } public Point getMid ( int x1, int y1, int x2, int y2) { Edge e= new Edge ( new Point ( x1, y1) , new Point ( x2, y2) ) ; Point p= hm. get ( e) ; if ( p!= null ) { return p; } p= new Point ( ( x1+ x2) / 2 , ( y1+ y2) / 2 ) ; hm. put ( e, p) ; return p; } public void drawmidRect ( Graphics g, int x1, int y1, int x2, int y2, int x3, int y3, int rx, int ry) { if ( Math . abs ( x3- x2) < 80 || Math . abs ( y3- y1) < 80 ) { g. drawLine ( x1, y1, x2, y2) ; g. drawLine ( x1, y1, x3, y3) ; g. drawLine ( x2, y2, x3, y3) ; return ; } Point pm1= getMid ( x1, y1, x2, y2) ; Point pm2= getMid ( x2, y2, x3, y3) ; Point pm3= getMid ( x1, y1, x3, y3) ; if ( rx> 0 && ry> 0 ) { pm1. x+= random. nextInt ( rx* 2 ) - rx; pm1. y+= random. nextInt ( ry* 2 ) - ry; pm2. x+= random. nextInt ( rx* 2 ) - rx; pm2. y+= random. nextInt ( ry* 2 ) - ry; pm3. x+= random. nextInt ( rx* 2 ) - rx; pm3. y+= random. nextInt ( ry* 2 ) - ry; } int nr= Math . max ( 1 , rx/ 2 ) ; int ny= Math . max ( 1 , ry/ 2 ) ; drawmidRect ( g, x1, y1, pm1. x, pm1. y, pm3. x, pm3. y, nr, ny) ; drawmidRect ( g, pm1. x, pm1. y, x2, y2, pm2. x, pm2. y, nr, ny) ; drawmidRect ( g, pm3. x, pm3. y, pm2. x, pm2. y, x3, y3, nr, ny) ; drawmidRect ( g, pm1. x, pm1. y, pm2. x, pm2. y, pm3. x, pm3. y, nr, ny) ; } public static void main ( String [ ] args) { new Drawmid ( ) ; } }