※ JPA vs Spring Data JPA

// 순수 JPA
Optional<Member> m1 = memberJpaRepository.findById(1L); // 1L은 ID가 1, 타입은 Long을 의미
List<Member> actives1 = memberJpaRepository.findAllByStatus(Member.Status.ACTIVE);

// Spring Data JPA
Member m2 = memberRepository.findById(1L) // 1L은 ID가 1, 타입은 Long을 의미
              .orElseThrow(() -> new IllegalArgumentException("not found"));
List<Member> actives2 = memberRepository.findAllByStatus(Member.Status.ACTIVE);

 

※ JPA vs Spring Data JPA 비교 표

구분 순수 JPA (EntityManager) Spring Data JPA
소속 JPA 표준 API (자바 ORM 표준) JPA 기반의 스프링 모듈 (확장/편의 기능 제공)
단건 조회 메서드 em.find(Entity.class, pk) findById(pk)
반환 타입 엔티티 객체 (없으면 null) Optional<T> (없으면 Optional.empty())
null 처리 개발자가 직접 null 체크 Optional API로 null-safe 처리
쿼리 작성 방식 JPQL 직접 작성 필요 메서드 이름 기반 자동 생성 or @Query 사용
CRUD 기본 제공 없음 (직접 구현) save, findAll, deleteById 등 기본 CRUD 제공
페이징/정렬 JPQL로 직접 구현 Pageable, Sort 등 내장 지원
트랜잭션 관리 직접 제어 or 스프링 @Transactional 사용 동일 (스프링 @Transactional 사용)
코드량 비교적 많음 (보일러플레이트 존재) 간결 (리포지토리 인터페이스만 선언해도 사용 가능)
유연성 매우 높음 (JPA 모든 기능 직접 제어 가능) 편의성 높음, 하지만 일부 세밀 제어는 한계
학습 난이도 다소 높음 (JPA 문법과 JPQL 숙지 필요) 상대적으로 낮음 (자동화된 기능 덕분)

* 보일러플레이트 : 필수지만 매번 반복적으로 작성해야 하는 형식적인 코드

 

※ Spring Data JPA가 생산성을 높이는 3가지 핵심 이유

1) 트랜잭션과 EntityManager 자동 관리

· 순수 JPA에서는 EntityManager 생성, 트랜잭션 시작·종료, 예외 처리 등을 매번 작성해야 함
· Spring Data JPA는 스프링이 자동으로 주입하고, @Transactional로 트랜잭션을 간단하게 처리


2) 쿼리 자동 생성
· 순수 JPA는 JPQL을 직접 작성해야 함

· Spring Data JPA는 메서드 이름 기반으로 쿼리를 자동 생성

    · 예 : findAllByStatus(Status.ACTIVE) → select m from Member m where m.status = ? 자동 생성
· 필요하면 @Query로 직접 JPQL 또는 네이티브 쿼리 작성도 가능


3) 기본 CRUD와 페이징·정렬 내장

· save, findById, findAll, deleteById 같은 CRUD 메서드가 기본 제공
· Pageable, Sort를 활용한 페이징과 정렬 기능도 내장되어 있어 추가 구현이 필요 없음

 

※ 결론

Spring Data JPA는 순수 JPA의 복잡한 보일러플레이트 코드를 최소화하여, 개발자가 비즈니스 로직에만 집중할 수 있도록 도와줌

· 순수 JPA → 유연하지만 반복 코드 많음

· Spring Data JPA → 생산성 높고 유지보수성 향상

1. https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api 접속 후 버전 선택

 

 2. Maven 또는 Gradle에 맞게 dependency 추가

 

3. Update Project

// Date 변수 date1 -> yyyyMMdd 문자열로 변환
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String strDate1 = sdf.format(date1);

// LocalDate 변수 date2 -> yyyyMMdd 문자열로 변환
String strDate2 = date2.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

// LocalDateTime 변수 date3 -> yyyyMMdd 문자열로 변환
String strDate3 = date3.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

 

'Java > 참고자료' 카테고리의 다른 글

[Java] JPA vs Spring Data JPA  (2) 2025.08.09
[Java] javax.annotation.Resource 오류  (1) 2025.01.17
[Java] 특정 문자열 및 빈 값 체크  (0) 2024.08.29
[Java] Annotation  (0) 2023.08.15
[Java] Equals & HashCode  (0) 2022.11.25
// Java 특정 문자열 및 빈 값 체크
String str1 = null; // str1 == null로 체크
String str2 = "A"; // "A".equals(str2)로 체크
String str3 = ""; // "".equals(str3)로 체크
// (Java 6 이상)
String str4 = ""; // str4.isEmpty()로 체크
String str5 = ""; // str5.trim().isEmpty()로 체크
String str6 = " "; // str6.trim().isEmpty()로 체크
String str7 = "          "; // str7.trim().isEmpty()로 체크
// (Java 11 이상)
String str8 = ""; // str8.isBlank()로 체크
String str9 = " "; // str9.isBlank()로 체크
String str10 = "          "; // str10.isBlank()로 체크

'Java > 참고자료' 카테고리의 다른 글

[Java] javax.annotation.Resource 오류  (1) 2025.01.17
[Java] Date & LocalDate & LocalDateTime 변수를 yyyyMMdd 문자열로 변환  (0) 2024.09.13
[Java] Annotation  (0) 2023.08.15
[Java] Equals & HashCode  (0) 2022.11.25
[Java] Exception  (0) 2022.11.25

<객체 비교>

== : 동일성 비교(객체 인스턴스의 주소 값을 비교)

equals() : 동등성 비교(객체 내부의 값을 비교)

 

hashCode() : 객체의 메모리 번지를 이용해서 해시코드를 만들고 그 값을 리턴(객체마다 다른 값을 가지고 있다.)

hashCode()를 사용하는 이유 중 하나는, 객체를 비교할 때 드는 비용을 낮추기 위함이다.

자바에서 2개의 객체가 같은지 비교할 때 equals()를 사용하는데, 여러 객체를 비교할 때 equals()를 사용하면 Integer를 비교하는 것에 비해 많은 시간이 소요된다.

hashCode() 메소드를 실행하여 리턴된 해시코드 값이 다르면 다른 객체로 판단하고, 해시코드 값이 같으면 equals() 메소드로 두 객체를 다시 비교한다.

즉, 여러 객체의 동등성 비교를 할 때
hashCode() 메소드를 실행해 값이 같을 경우에만 equals() 메소드로 동등성을 비교하면 되는 것이다.
hashCode() 값이 다르면 애초에 비교할 필요가 없게 된다.

 

hashCode가 다르면, 두개의 객체가 같지 않다.

hashCode가 같으면, 두개의 객체가 같거나 다를 수 있다.

 

<equals()와 hashCode()를 같이 재정의해야 하는 이유>

1. hashCode()를 재정의 하지 않으면 같은 값 객체라도 해시값이 다를 수 있다. 따라서 HashTable에서 해당 객체가 저장된 버킷을 찾을 수 없다.

2. equals()를 재정의하지 않으면 hashCode()가 만든 해시값을 이용해 객체가 저장된 버킷을 찾을 수는 있지만 해당 객체가 자신과 같은 객체인지 값을 비교할 수 없기 때문에 null을 리턴하게 된다.

 

<equals()만 재정의>

public class Test {
	String name;
	
	public Test(String name) {
		this.name = name;
	}

	@Override
	public boolean equals(Object obj) {
		Test otherTest = (Test) obj;
		return (this.name.equals(otherTest.name));
	}
}
import java.util.HashMap;

public class EqualsAndHashCode {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "Z@S.ME";
		String str2 = "Z@RN.E";
		
		HashMap<String, Integer> hm1 = new HashMap<>();
		
		hm1.put(str1, 30);
		hm1.put(str2, 40);
		System.out.println(str1.equals(str2)); // false
		System.out.println(str1.hashCode()); // -1656719047
		System.out.println(str2.hashCode()); // -1656719047
		System.out.println(hm1.size()); // 2
		System.out.println(hm1.get(str1)); // 30
		System.out.println(hm1.get(str2)); // 40
		
		Test test1 = new Test("abcd");
		Test test2 = new Test(new String("abcd"));
		
		HashMap<Test, Integer> hm2 = new HashMap<>();
		
		hm2.put(test1, 10);
		hm2.put(test2, 20);
		System.out.println(test1.equals(test2)); // true
		System.out.println(test1.hashCode()); // 474675244
		System.out.println(test2.hashCode()); // 932583850
		System.out.println(hm2.size()); // 2
		System.out.println(hm2.get(test1)); // 10
		System.out.println(hm2.get(test2)); // 20
	}
}

<hashcode()만 재정의>

public class Test {
	String name;
	
	public Test(String name) {
		this.name = name;
	}
	
	@Override
	public int hashCode() {
		int hashCode = 0;
		hashCode = 31 * hashCode + ((name == null) ? 0 : name.hashCode());
		return hashCode;
	}
}
import java.util.HashMap;

public class EqualsAndHashCode {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "Z@S.ME";
		String str2 = "Z@RN.E";
		
		HashMap<String, Integer> hm1 = new HashMap<>();
		
		hm1.put(str1, 30);
		hm1.put(str2, 40);
		System.out.println(str1.equals(str2)); // false
		System.out.println(str1.hashCode()); // -1656719047
		System.out.println(str2.hashCode()); // -1656719047
		System.out.println(hm1.size()); // 2
		System.out.println(hm1.get(str1)); // 30
		System.out.println(hm1.get(str2)); // 40
		
		Test test1 = new Test("abcd");
		Test test2 = new Test(new String("abcd"));
		
		HashMap<Test, Integer> hm2 = new HashMap<>();
		
		hm2.put(test1, 10);
		hm2.put(test2, 20);
		System.out.println(test1.equals(test2)); // false
		System.out.println(test1.hashCode()); // 2987074
		System.out.println(test2.hashCode()); // 2987074
		System.out.println(hm2.size()); // 2
		System.out.println(hm2.get(test1)); // 10
		System.out.println(hm2.get(test2)); // 20
	}
}

<equals()와 hashcode() 모두 재정의>

public class Test {
	String name;
	
	public Test(String name) {
		this.name = name;
	}

	@Override
	public boolean equals(Object obj) {
		Test otherTest = (Test) obj;
		return (this.name.equals(otherTest.name));
	}
	
	@Override
	public int hashCode() {
		int hashCode = 0;
		hashCode = 31 * hashCode + ((name == null) ? 0 : name.hashCode());
		return hashCode;
	}
}
import java.util.HashMap;

public class EqualsAndHashCode {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "Z@S.ME";
		String str2 = "Z@RN.E";
		
		HashMap<String, Integer> hm1 = new HashMap<>();
		
		hm1.put(str1, 30);
		hm1.put(str2, 40);
		System.out.println(str1.equals(str2)); // false
		System.out.println(str1.hashCode()); // -1656719047
		System.out.println(str2.hashCode()); // -1656719047
		System.out.println(hm1.size()); // 2
		System.out.println(hm1.get(str1)); // 30
		System.out.println(hm1.get(str2)); // 40
		
		Test test1 = new Test("abcd");
		Test test2 = new Test(new String("abcd"));
		
		HashMap<Test, Integer> hm2 = new HashMap<>();
		
		hm2.put(test1, 10);
		hm2.put(test2, 20);
		System.out.println(test1.equals(test2)); // true
		System.out.println(test1.hashCode()); // 2987074
		System.out.println(test2.hashCode()); // 2987074
		System.out.println(hm2.size()); // 1
		System.out.println(hm2.get(test1)); // 20
		System.out.println(hm2.get(test2)); // 20
	}
}

equals()만 재정의 : equals()가 true이고, hashCode()가 다른 경우 => HashMap에서 다른 key로 인식

hashCode()만 재정의 : equals()가 false이고, hashCode()가 같은 경우 => HashMap에서 다른 key로 인식

equals()와 hashCode() 모두 재정의 : equals()가 true이고, hashCode()가 같은 경우 => HashMap에서 같은 key로 처리

'Java > 참고자료' 카테고리의 다른 글

[Java] 특정 문자열 및 빈 값 체크  (0) 2024.08.29
[Java] Annotation  (0) 2023.08.15
[Java] Exception  (0) 2022.11.25
[Java] Comparable & Comparator  (0) 2022.11.25
[Java] 연산자  (0) 2022.11.25
public class ExceptionOccurred {
	
	// Checked Exception : RuntimeException을 상속받지 않은 클래스
	// Unchecked Exception : RuntimeException을 상속받은 클래스
	// throw : 강제로 예외를 발생시킬 수 있음 단, 발생시킨 예외를 catch문에서 잡을 수 있는 처리가 되어있지 않으면 오류 발생(catch문의 Exception은 모든 예외를 잡을 수 있음)
	// throws : 예외 발생 시 자신을 호출한 상위 메소드로 예외를 던짐(특정 상위 메소드에서 예외를 한 번에 처리하는 경우가 있을 수 있음, 계속 throws로 던질 경우 최종적으로 JVM이 처리를 하게 되지만, 권장하지 않음)
	// 중요 : RuntimeException을 상속받은 Unchecked Exception의 경우 throws는 아무 의미 없음, throws는 Checked Exception의 처리 방법 중 하나
	
	public void method1() throws Exception {
		// 이 메소드를 호출한 부분의 catch문에 Exception에 대한 에외 처리가 있어야 함
		throw new Exception("강제로 예외 발생"); // 모든 예외를 잡을 수 있는 Exception의 경우 throws Exception 필수
	}
	
	// RuntimeException을 상속받은 NullPointerException
	public void method2() {
		// 이 메소드를 호출한 부분의 catch문에 Exception 또는 NullPointerException에 대한 예외 처리가 있어야 함
		throw new NullPointerException("강제로 NullPointerException 발생"); // NullPointerException 발생
	}
	
	// RuntimeException을 상속받은 ArithmeticException
	public void method3() {
		// 이 메소드를 호출한 부분의 catch문에 Exception 또는 ArithmeticException에 대한 예외 처리가 있어야 함
		System.out.println(3 / 0); // ArithmeticException 발생
	}
	
	// RuntimeException을 상속받은 NullPointerException 발생이므로 throws는 아무 의미 없음
	public void method4() throws ArithmeticException {
		throw new NullPointerException("강제로 NullPointerException 발생"); // NullPointerException 발생
	}
	
	// RuntimeException을 상속받은 NullPointerException 발생이므로 throws는 아무 의미 없음
	public void method5() throws ArithmeticException {
		String name = null;
		System.out.println(name.length());
	}
	
	// ArithmeticException : 어떤 수를 0으로 나눌 때 발생(RuntimeException 상속)
	// NullPointerException : NULL 객체를 참조할 때 발생(RuntimeException 상속)
	// ClassCastException : 적절하지 못하게 클래스를 형 변환하는 경우 발생(RuntimeException 상속)
	// NegativeArraySizeException : 배열의 크기가 음수 값인 경우 발생(RuntimeException 상속)
	// IndexOutOfBoundsException : 리스트형 객체에서 선언되지 않은 요소를 가져오려고 할 때 발생(RuntimeException 상속)
}
public class ExceptionTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String name = null;
		
		ExceptionOccurred exceptionOccurred = new ExceptionOccurred();
		
		try {
			int nameLength = name.length(); // 1. NullPointerException에 걸리고 finally 실행
			int num = 3 / 0; // 2. 코드 1이 없다면 ArithmeticException에 걸리고 finally 실행
			exceptionOccurred.method2(); // 3. 코드 1, 2가 없다면 NullPointerException에 걸리고 finally 실행
			exceptionOccurred.method3(); // 4. 코드 1, 2, 3이 없다면 ArithmeticException에 걸리고 finally 실행
		} catch (NullPointerException e) {
			System.out.println("NullPointerException : " + e.getMessage());
		} catch (ArithmeticException e1) {
			System.out.println("ArithmeticException : " + e1.getMessage());
		} catch (Exception e) { // try문 실행에서 발생하는 예외 중 NullPointerException, ArithmeticException 외의 예외는 이곳에 걸림
			System.out.println("Exception : 모든 예외를 잡을 수 있음");
		} finally { // 무조건 실행시킬 코드를 적는 부분
			System.out.println("무조건 실행되는 부분");
		}
		
		try {	
			int nameLength = name.length(); // 1. Exception에 걸리고 finally 실행
			int num = 3 / 0; // 2. 코드 1이 없다면 Exception에 걸리고 finally 실행
			exceptionOccurred.method1(); // 3. 코드 1, 2가 없다면 Exception에 걸리고 finally 실행
			throw new Exception("강제 예외 발생"); // 4. 코드 1, 2, 3이 없다면 Exception에 걸리고 finally 실행
//			exceptionOccurred.method2(); // 5. 코드 1, 2, 3, 4가 없다면 Exception에 걸리고 finally 실행
//			exceptionOccurred.method3(); // 6. 코드 1, 2, 3, 4, 5가 없다면 Exception에 걸리고 finally 실행
		} catch (Exception e) { // try문 실행에서 발생하는 모든 예외를 잡을 수 있지만, 어떤 문제로 발생하는 예외인지 확인이 불가하다는 단점이 있다.
			System.out.println("Exception : 모든 예외를 잡을 수 있음");
		} finally { // 무조건 실행시킬 코드를 적는 부분
			System.out.println("무조건 실행되는 부분");
		}
	}
}

Checked Exception : RuntimeException을 상속받지 않은 클래스

Unchecked Exception : RuntimeException을 상속받은 클래스

throw : 강제로 예외를 발생시킬 수 있음 단, 발생시킨 예외를 catch문에서 잡을 수 있는 처리가 되어있지 않으면 오류 발생(catch문의 Exception은 모든 예외를 잡을 수 있음)

throws : 예외 발생 시 자신을 호출한 상위 메소드로 예외를 던짐(특정 상위 메소드에서 예외를 한 번에 처리하는 경우가 있을 수 있음, 계속 throws로 던질 경우 최종적으로 JVM이 처리를 하게 되지만, 권장하지 않음)

 

중요 : RuntimeException을 상속받은 Unchecked Exception의 경우 throws는 아무 의미 없음

throws는 Checked Exception의 처리 방법 중 하나

 

 

'Java > 참고자료' 카테고리의 다른 글

[Java] Annotation  (0) 2023.08.15
[Java] Equals & HashCode  (0) 2022.11.25
[Java] Comparable & Comparator  (0) 2022.11.25
[Java] 연산자  (0) 2022.11.25
[Java] Stack, Queue, Deque  (0) 2022.11.25

Comparable : 현재 객체와 다른 객체의 비교 기준을 정함 => Comparable - CompareTo (T o) 정의

Comparator : 두 객체의 비교 기준을 정함 => Comparator - Compare(T o1, T o2) 정의

 

<Comparable>

public class Node implements Comparable<Node> {
	
	private int index = 0; // 노드의 번호
	private int distance = 0; // 노드의 거리
	private String name = ""; // 노드의 이름
	
	public Node(int index, int distance, String name) {
		this.index = index;
		this.distance = distance;
		this.name = name;
	}
	
	public int getIndex() {
		return this.index;
	}
	
	public int getDistance() {
		return this.distance;
	}
	
	public String getName() {
		return this.name;
	}

	@Override
	public int compareTo(Node otherNode) {
		// TODO Auto-generated method stub
		// private 변수이지만 클래스 내부에선 getDistance()로 가져올 필요 없이 직접 가져와도 됨
//		return this.distance - otherNode.distance; // distance 기준 오름차순 정렬 // 1, 2, 3, ...
//		return this.getDistance() - otherNode.getDistance(); // distance 기준 오름차순 정렬 // 1, 2, 3, ...
//		return otherNode.distance - this.distance; // distance 기준 내림차순 정렬 // ..., 3, 2, 1
//		return otherNode.getDistance() - this.getDistance(); // distance 기준 내림차순 정렬 // ..., 3, 2, 1
		
		// distance, index, name 기준 오름차순 정렬(ORDER BY distance, index, name)
		if (this.distance == otherNode.distance) { // distance가 같을 경우
			
			if (this.index == otherNode.index) { // index가 같을 경우
				return this.name.compareTo(otherNode.name); // name 기준 오름차순 정렬
//				return otherNode.name.compareTo(this.name); // name 기준 내림차순 정렬
			} else { // index가 같지 않을 경우
				return this.index - otherNode.index; // index 기준 오름차순 정렬
//				return otherNode.index - this.index; // index 기준 내림차순 정렬
			}
		} else { // distance가 같지 않을 경우
			return this.distance - otherNode.distance; // distance 기준 오름차순 정렬
//			return otherNode.distance - this.distance; // distance 기준 내림차순 정렬
		}
		
//		// int 값으로 비교 : return int - int;
//		// String 값으로 비교 : return String.compareTo(String);
//		------------------------------------------------------------------------------------------------------
//		// distance 값을 기준으로 오름차순 정렬을 시키는 다른 방법 1, 2, 3, ...
//		if (this.distance < otherNode.distance) {
//			return -1; // 해당 노드의 거리가 비교대상 노드의 거리보다 작다면 => 해당 노드가 더 작다 리턴
//		}
//		
//		return 1; // 해당 노드의 거리가 비교대상 노드의 거리보다 크거나 같다면 => 해당 노드가 더 크다 리턴
//		
//		// distance 값을 기준으로 내림차순 정렬을 시키는 다른 방법 ..., 3, 2, 1
//		if (this.distance < otherNode.distance) {
//			return 1; // 해당 노드의 거리가 비교대상 노드의 거리보다 작다면 => 해당 노드가 더 크다 리턴
//		}
//		
//		return -1; // 해당 노드의 거리가 비교대상 노드의 거리보다 크거나 같다면 => 해당 노드가 더 작다 리턴
//		
//		// int 값으로 비교 : 1(크다), 0(같다), -1(작다)
//		// String 값으로 비교 : 0(같다), 다양한 양수/음수 값 : 대상 문자열의 제일 앞 부분부터 비교하여 비교대상 문자열을 포함한다면 문자열 길이 차만큼 리턴, 하지만 아예 포함하지 않거나, 중간에 포함한다면 각 문자열의 제일 앞 아스키 코드값의 차를 리턴(대상 문자열 첫 문자 아스키코드 값 - 비교대상 문자열 첫 문자 아스키코드 값)
//		------------------------------------------------------------------------------------------------------
	}
}
import java.util.*;

public class ComparableTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// --------------------------------------일반 배열--------------------------------------
		int[] arr1 = {2, 1, 6, 3, 7, 4, 5};
		
		for (int num : arr1) {
			System.out.print(num + " "); // 2 1 6 3 7 4 5 
		}
		
		System.out.println();
		// --------------------------------------배열 정렬--------------------------------------
		Arrays.sort(arr1); // 기본 오름차순 정렬
		
		for (int num : arr1) {
			System.out.print(num + " "); // 1 2 3 4 5 6 7 
		}
		
		System.out.println();
		// ------------------------Comparable 인터페이스를 구현한 Node 클래스------------------------
		ArrayList<Node> list = new ArrayList<>();
		
		// index, distance, name
		list.add(new Node(1, 2, "B"));
		list.add(new Node(2, 1, "A"));
		list.add(new Node(2, 2, "C"));
		list.add(new Node(1, 3, "F"));
		list.add(new Node(1, 3, "E"));
		list.add(new Node(1, 3, "D"));
		
		for (Node node : list) {
			System.out.print(node.getName() + " "); // "B", "A", "C", "F", "E", "D"
		}
		
		System.out.println();
		// -----------------------------------Node 클래스 정렬-----------------------------------
		Collections.sort(list); // Node 클래스의 정렬 기준 : ORDER BY distance, index, name
		
		for (Node node : list) {
			System.out.print(node.getName() + " "); // "A", "B", "C", "D", "E", "F"
		}
	}
}

<Comparator>

public class Node {
	
	private int index = 0; // 노드의 번호
	private int distance = 0; // 노드의 거리
	
	public Node(int index, int distance) {
		this.index = index;
		this.distance = distance;
	}
	
	public int getIndex() {
		return this.index;
	}
	
	public int getDistance() {
		return this.distance;
	}
}
import java.util.*;

public class ComparatorTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// -------------------------------------Node 클래스-------------------------------------
		ArrayList<Node> list = new ArrayList<>();
		
		list.add(new Node(2, 2));
		list.add(new Node(1, 1));
		list.add(new Node(3, 3));
		
		for (Node node : list) {
			System.out.print(node.getDistance() + " "); // 2, 1, 3
		}
		
		System.out.println();
		// -----------------------------------Node 클래스 정렬-----------------------------------
		Collections.sort(list, new Comparator<Node>() {
			@Override
			public int compare(Node node1, Node node2) {
				// distance 기준 오름차순 정렬 // 1, 2, 3, ...
				if(node1.getDistance() < node2.getDistance()) return -1;
				else if(node1.getDistance() == node2.getDistance()) return 0;
				else return 1;
				
				// distance 기준 내림차순 정렬 // ..., 3, 2, 1
//				if(node1.getDistance() < node2.getDistance()) return 1;
//				else if(node1.getDistance() == node2.getDistance()) return 0;
//				else return -1;
				
				// distance는 Node 클래스의 private 변수이므로 node1.distance가 아닌 distance 값을 가져오도록 만든 node1.getDistance() 메소드 사용
			}
		});
		
		for (Node node : list) {
			System.out.print(node.getDistance() + " "); // 1, 2, 3
		}
	}
}

<2차원 배열에서 다중 정렬>

int[][] arr = {{1, 3}, {1, 2}, {3, 4}, {1, 4}, {2, 4}};

Arrays.sort(arr, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        if(o1[0] == o2[0]) { // 앞 원소가 같을 경우
            return o1[1] - o2[1]; // 뒤 원소 기준 오름차순
//          return o2[1] - o1[1]; // 뒤 원소 기준 내림차순
        }else { // 앞 원소가 같지 않을 경우
            return o1[0] - o2[0]; // 앞 원소 기준 오름차순
//          return o2[0] - o1[0]; // 앞 원소 기준 내림차순
        }
    }
});

 

 

<Comparable 인터페이스의 compareTo 메소드 구현 시 타입 비교>

 

'Java > 참고자료' 카테고리의 다른 글

[Java] Equals & HashCode  (0) 2022.11.25
[Java] Exception  (0) 2022.11.25
[Java] 연산자  (0) 2022.11.25
[Java] Stack, Queue, Deque  (0) 2022.11.25
[Java] 참고자료  (0) 2022.11.25

<비트 연산자>

// 비트 연산자
System.out.println(1 << 5); // 1 -> 100000 // 32
System.out.println(2 << 5); // 10 -> 1000000 // 64
System.out.println(10 >> 1); // 1010 -> 101 // 5
System.out.println(10 >> 2); // 1010 -> 10 // 2
System.out.println(1 << 5 & 1 << 3); // 100000 & 1000 // 모두 1인 경우만 1로 => 000000 // 0
System.out.println(13 & 9); // 1101 & 1001 // 모두 1인 경우만 1로 => 1001 // 9
System.out.println(1 << 5 | 1 << 3); // 100000 | 1000 // 하나라도 1이면 1로 => 101000 // 40
System.out.println(13 | 9); // 1101 | 1001 // 하나라도 1이면 1로 => 1101 // 13
System.out.println(13 ^ 9); // 1101 ^ 1001 // 모두 같으면 0, 다르면 1로 => 100 // 4
System.out.println(~13); // ~1101 // 8비트로 만든 후 0과 1 바꿈 => 00001101 => 11110010 // -14
// 2의 보수 = 1의 보수(0과 1 바꿈) + 1
// 10진수 -14를 2진수로 표현
// 14를 8비트로 만든다. 00001110
// -14는 음수이므로 첫 번째 부호 비트를 1로 바꾼다. 10001110
// 부호 비트만 그대로 유지하고 0과 1을 바꾼다.(1의 보수) 11110001
// 1을 더한다. 11110010

'Java > 참고자료' 카테고리의 다른 글

[Java] Exception  (0) 2022.11.25
[Java] Comparable & Comparator  (0) 2022.11.25
[Java] Stack, Queue, Deque  (0) 2022.11.25
[Java] 참고자료  (0) 2022.11.25
[Java] 소수  (0) 2022.11.25

+ Recent posts