트러블 슈팅
HashSet의 객체 중복 제거
yougeun
2022. 10. 22. 23:20
728x90
public class VisitLength { //방문길이
public static void main(String[] args) {
String dirs = "ULURRDLLU";
System.out.println(solution(dirs));
}
public static int solution(String dirs) {
Coordinate coordinate = new Coordinate(0,0);
HashSet<Coordinate> hashSet = new HashSet<>();
for(int i=0; i<dirs.length();i++){
switch (dirs.charAt(i)){
case 'U':
if(coordinate.getY()+1<=5){
coordinate.update(0,1);
hashSet.add(new Coordinate(coordinate.getX(), coordinate.getY()-0.5));
}
break;
case 'D':
if(coordinate.getY()-1>=-5){
coordinate.update(0,-1);
hashSet.add(new Coordinate(coordinate.getX(), coordinate.getY()+0.5));
}
break;
case 'L':
if(coordinate.getX()-1>=-5){
coordinate.update(-1,0);
hashSet.add(new Coordinate(coordinate.getX()+0.5, coordinate.getY()));
}
break;
case 'R':
if(coordinate.getX()+1<=5){
coordinate.update(1,0);
hashSet.add(new Coordinate(coordinate.getX()-0.5, coordinate.getY()));
}
break;
}
for(Coordinate c: hashSet){
System.out.println("x:"+c.getX()+" y:"+c.getY());
}
System.out.println();
}
return hashSet.size();
}
static class Coordinate{
double x;
double y;
public Coordinate(double x,double y){
this.x = x;
this.y = y;
}
public void update(double x, double y){
this.x+=x;
this.y+=y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Coordinate){
Coordinate coordinate = (Coordinate) obj;
return (this.x ==coordinate.x && this.y == coordinate.y);
}
return false;
}
@Override
public int hashCode() {
return (this.x+""+this.y).hashCode();
}
프로그래머스 방문길이를 푸는 도중 HashSet에 객체를 넣어 객체의 x좌표와 y좌표가 같을 경우 중복으로 인식하여 같은 객체가 저장되지 않도록 해야 했다. 기존 방법처럼 add함수를 통해 넣을 경우 x좌표와 y좌표 같음에도 불구하고 저장되어있는 것을 볼 수 있었다. 찾아본 결과 HashSet에 객체가 들어갈떄마다 hashCode()와 equals() 메서드를 실행한다는 것을 알게 되었다. 처음 hashCode() 메서드를 통해 hashCode가 같은지 판별하고 같을 경우 equals() 메서드를 실행하여 같은지 판별한다. 그래서 Coordinate에 equals() 메서드와 hashCode() 메서드를 구현하여 중복제거를 할 수 있었다.
728x90