我的代码中有一个HashSet,它使用自定义类型Line,其中Line有四个整数字段(x1,y1,x2,y2;所有字段代表行的起点和终点的坐标).我使用大量这些行填充HashSet.然后我想稍后删除特定的行.我试过调用HashSet.remove(新行(正确的属性)),但失败了.关于如何做到这一点的任何想法?
附件是参考代码.该类试图实现Aldous-Broder迷宫生成器,这样最初所有墙都被填充到集合中,然后移除墙(因为该方法雕刻迷宫路径),然后传递给绘图机制.
package tests;
import java.util.HashSet;
import java.util.Random;
public class AldousBroderTest {
static HashSet<Line> walls = new HashSet<Line>();
static Random rn = new Random();
public static void generateWalls(int x1, int y1, int x2, int y2){
for (int i = x1; i < x2; i += 10){
for (int j = y1; j < y2; j += 10){
walls.add(new Line(i, j, i + 10, j));
walls.add(new Line(i,j,i,j+10));
}
}
walls.add(new Line(x1, y1, x1, y2));
walls.add(new Line(x1, y1, x2, y1));
walls.add(new Line(x2, y1, x2, y2));
walls.add(new Line(x1, y2, x2, y2));
}
public static void generateMaze(int x1, int y1, int x2, int y2){
boolean[][] visited = new boolean[x2-x1][y2-y1];
int counter = 1;
int currentx = rn.nextInt((x2-x1)/10)*10;
int currenty = rn.nextInt((y2-y1)/10)*10;
visited[currentx][currenty] = true;
int cellcount = (x2-x1)/10 * (y2-y1)/10;
System.out.println(cellcount);
while (counter < cellcount){
int direction = rn.nextInt(4);
switch (direction){
case 0:
if(currenty == y1){break;}
currenty -= 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx, currenty+10, currentx+10, currenty+10));
}
break;
case 1:
if(currentx+10 == x2){break;}
currentx += 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx, currenty, currentx, currenty+10));
}
break;
case 2:
if(currenty+10 == y2){break;}
currenty += 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx, currenty, currentx+10, currenty));
}
break;
case 3:
if(currentx == x1){break;}
currentx -= 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx+10, currenty, currentx+10, currenty+10));
}
break;
}
}
}
public static void main(String[] args){
generateWalls(0,0,50,50);
generateMaze(0,0,50,50);
Frame frame = new Frame(walls);
}
}
Run Code Online (Sandbox Code Playgroud)
在类Line中,重写equals和hascode方法.
@Override
public boolean equals(Object obj) {
// equals code
}
@Override
public int hashCode() {
// hascode method
}
Run Code Online (Sandbox Code Playgroud)
在这里你可以找到"为什么要实现这两个方法"的解释为什么我需要覆盖Java中的equals和hashCode方法?
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |