[Java 16-7 StudentSetApp] 학생정보(학번,이름)를 저장하기 위한 클래스 - VO(Value Object) 클래스

임승현·2022년 10월 19일

Java

목록 보기
81/126

🐧학생정보(학번,이름)를 저장하기 위한 클래스 - VO(Value Object) 클래스

→ 객체의 컬럼값을 비교하기 위한 기능을 제공받기 위해 Comparable 인터페이스를 상속받아 작성

package xyz.itwill.util;

public class Student implements Comparable<Student> {
	private int num;
	private String name;
	
	public Student() {
		// TODO Auto-generated constructor stub
	}

	public Student(int num, String name) {
		super();
		this.num = num;
		this.name = name;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	//Object 클래스의 toString() 메소드를 오버라이드 선언
	// => VO 클래스에 저장된 필드값을 반환받아 확인하기 위해 선언
	@Override
	public String toString() {
		return "학번 = "+num+", 이름 = "+name;
	}
	
	//Object 클래스의 hashCode() 메소드를 오버라이드 선언
	// => 객체의 메모리 주소 대신 VO 클래스의 필드값을 반환
	@Override
	public int hashCode() {
		return num;
	}
		
	//Object 클래스의 equals() 메소드를 오버라이드 선언
	// => VO 클래스에 저장된 필드값을 비교하여 결과를 반환하기 위해 사용
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Student) {
			//매개변수로 전달받은 객체를 명시적 객체 형변환하여 참조변수에 저장
			Student student=(Student)obj;
			
			//메소드의 객체(this)와 매개변수로 전달받은 객체(obj)의 필드값을 비교하여 논리값 반환
			// => 학번를 비교하여 같은 경우 [true] 반환
			if(num==student.num) return true;
		}
		//비교가 불가능하거나 학번이 다른 경우 [false] 반환
		return false;
	}
	
	//객체의 컬럼값을 매개변수로 전달받은 객체의 컬럼값과 비교하여 결과를 반환하는 메소드
	//→ 객체의 컬럼값이 큰 경우 양수 반환하고 매개변수로 전달받은 객체의 컬럼값이 
    큰 경우 음수 반환되며 같은 경우 0을 반환되도록 명령 작성
	//→ 오름차순 또는 내림차순 정렬을 위한 비교값 설정
	@Override
	public int compareTo(Student o) {
		// TODO Auto-generated method stub
		return this.num-o.num;//학번을 비교하여 오름차순 정렬되도록 설정(this 생략 가능)
		//return this.o.num-num;//학번을 비교하여 내림차순 정렬되도록 설정(this 생략 가능)
		//return name.compareTo(o.name);//이름을 비교하여 오름차순 정렬되도록 설정
		//return o.name.compareTo(name);//이름을 비교하여 내림차순 정렬되도록 설정
	}
}
package xyz.itwill.util;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class StudentSetApp {
	public static void main(String[] args) {
		Set<Student> studentSet=new HashSet<Student>();
		
		studentSet.add(new Student(1000, "홍길동"));
		studentSet.add(new Student(2000, "임꺽정"));
		studentSet.add(new Student(3000, "전우치"));
		//Set 객체에 동일한 값이 저장된 Student 객체가 요소로 저장 가능
		//→ Student 객체에 저장된 값은 같지만 객체는 다르므로 요소로 저장 가능
		//hashCode() 메소드와 equals() 메소드를 오버라이드 선언하여 동일한 값이 
        저장된 객체를 Set 객체의 요소로 저장하지 않도록 설정 가능
		//→ 매개변수로 전달받은 객체를 기존 요소의 HashCode와 비교하고 같은 경우 
        필드값을 비교하여 같으면 저장되지 않도록 Set 객체 동작
		//studentSet.add(new Student(1000, "홍길동"));//학번이 같은 학생정보 정장 불가능
		studentSet.add(new Student(4000, "홍길동"));
		Iterator<Student> iterator=studentSet.iterator();
		
		while (iterator.hasNext()) {
			//객체를 반환받아 출력할 경우 Student.toString() 메소드 자동 호출
			System.out.println(iterator.next());
		}	
	}
}

0개의 댓글