개발/JAVA

[JAVA] Vector<Point> 컬렉션 예제, toString 메소드 재정의

윤J 2022. 10. 26. 01:12
import java.util.Vector;

class Point{
	private int x, y;
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	public String toString() {// toString()메소드: 객체를 문자열로 만들어 출력하는~ 재정의
		return "("+x+","+y+")";
	}
}


public class PointerVectorEx {
	public static void main(String [] args) {
		
		Vector<Point> v = new Vector<Point>();//Point 객체를 요소로만 가지는 벡터 생성
		// 약간 Point v 느낌이라고 생각하면 됨
		
		v.add(new Point(2, 3));
		v.add(new Point(-5, 20));
		v.add(new Point(30, -8));
		
		v.remove(1);
		
		for(int i = 0; i<v.size(); i++) {
			Point p = v.get(i); // p는 Point(-5, 20) 임
			System.out.println(p); // p는 p.toString 으로 자동 변환!
			
		}
	}
}

실행결과

(2,3)

(30,-8)