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

 

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

 

3. Update Project

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

[Java] Date & LocalDate & LocalDateTime 변수를 yyyyMMdd 문자열로 변환  (0) 2024.09.13
[Java] 특정 문자열 및 빈 값 체크  (0) 2024.08.29
[Java] Annotation  (0) 2023.08.15
[Java] Equals & HashCode  (0) 2022.11.25
[Java] Exception  (0) 2022.11.25
// 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] 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] Exception  (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
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class DequeSample {
	
	// Stack, Queue, Deque

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Deque<Integer> stack1 = new ArrayDeque<>(); // addFirst + removeFirst // 스택
		
		stack1.addFirst(1);
		stack1.addFirst(2);
		stack1.addFirst(3);
		
//		stack1.add(4); // add는 addLast와 같음 // addFirst로 쌓고 있었는데 그 방향과 반대 방향에 추가 4, 1, 2, 3이 됨
//		stack1.addFirst(5); // 1, 2, 3과 같은 방향으로 추가 // 4, 1, 2, 3, 5
//		stack1.addLast(6); // addFirst와 반대 방향으로 추가 // 6, 4, 1, 2, 3, 5
		
		System.out.println("stack1"); // stack1
		
		System.out.println(stack1.peekFirst()); // 3
		System.out.println(stack1.removeFirst()); // 3
		System.out.println(stack1.removeFirst()); // 2
		System.out.println(stack1.removeFirst()); // 1
		
		Deque<Integer> queue1 = new ArrayDeque<>(); // addFirst + removeLast // 큐
		
		queue1.addFirst(1);
		queue1.addFirst(2);
		queue1.addFirst(3);
		
		System.out.println("queue1"); // queue1
		
		System.out.println(queue1.peekLast()); // 1
		System.out.println(queue1.removeLast()); // 1
		System.out.println(queue1.removeLast()); // 2
		System.out.println(queue1.removeLast()); // 3
		
		Deque<Integer> queue2 = new ArrayDeque<>(); // addLast + removeFirst // 큐
		
		queue2.addLast(1);
		queue2.addLast(2);
		queue2.addLast(3);
		
		System.out.println("queue2"); // queue2
		
		System.out.println(queue2.peekFirst()); // 1
		System.out.println(queue2.removeFirst()); // 1
		System.out.println(queue2.removeFirst()); // 2
		System.out.println(queue2.removeFirst()); // 3
		
		Deque<Integer> stack2 = new ArrayDeque<>(); // addLast + removeLast // 스택
		
		stack2.addLast(1);
		stack2.addLast(2);
		stack2.addLast(3);
		
		System.out.println("stack2"); // stack2
		
		System.out.println(stack2.peekLast()); // 3
		System.out.println(stack2.removeLast()); // 3
		System.out.println(stack2.removeLast()); // 2
		System.out.println(stack2.removeLast()); // 1
		
		// Deque 자료구조에서 확인할 수 있는 사실
		// add(A) + peek(B) or remove(B)가 있을 때 // (A)와 (B)는 First 또는 Last
		// (A)와 (B)가 같다면 스택(Stack)처럼 동작
		// (A)와 (B)가 다르다면 큐(Queue)처럼 동작
		// First + First, Last + Last => 스택(Stack)
		// First + Last, Last + First => 큐(Queue)
		// addFirst로 쌓고 있는 구조에서 제일 앞에 원소를 추가하고 싶다면 addLast로 추가
		// addLast로 쌓고 있는 구조에서 제일 앞에 원소를 추가하고 싶다면 addFirst로 추가
		
		Stack<Integer> stack = new Stack<>();
		
		stack.push(1);
		stack.push(2);
		stack.push(3);
		
		System.out.println("Original Stack"); // Original Stack
		System.out.println(stack.peek()); // 3
		System.out.println(stack.pop()); // 3
		System.out.println(stack.pop()); // 2
		System.out.println(stack.pop()); // 1
		
		Queue<Integer> queue = new LinkedList<>();
		
		queue.offer(1);
		queue.offer(2);
		queue.offer(3);
		
		System.out.println("Original Queue"); // Original Queue
		System.out.println(queue.peek()); // 1
		System.out.println(queue.poll()); // 1
		System.out.println(queue.poll()); // 2
		System.out.println(queue.poll()); // 3
	}
}

<Deque 자료구조>
add(A) + peek(B) or remove(B)가 있을 때 // (A)와 (B)는 First 또는 Last
(A)와 (B)가 같다면 스택(Stack)처럼 동작
(A)와 (B)가 다르다면 큐(Queue)처럼 동작
First + First, Last + Last => 스택(Stack)
First + Last, Last + First => 큐(Queue)
addFirst로 쌓고 있는 구조에서 제일 앞에 원소를 추가하고 싶다면 addLast로 추가
addLast로 쌓고 있는 구조에서 제일 앞에 원소를 추가하고 싶다면 addFirst로 추가

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

[Java] Comparable & Comparator  (0) 2022.11.25
[Java] 연산자  (0) 2022.11.25
[Java] 참고자료  (0) 2022.11.25
[Java] 소수  (0) 2022.11.25
[Java] Class 기본 구조  (0) 2022.11.25

+ Recent posts