//검색 intindexOf(Object o); // 못 찾으면 -1 intlastIndexOf(Object o); booleancontains(Object o); Object get(int index); // 특정 위치 객체 읽기 Object set(int index, Object element); // 특정 위치 객체 변경
예: int arr -> 1, 2, 3, 4, 5 이면 n번째 arr 주소 + 4 byte * n
단점1: 크기 변경시 데이터 복사가 일어남
단점2: 비순차적 데이터 추가 삭제에 시간이 많이 걸린다, 맨끝에 하는것 제외
LinkedList는 배열의 단점 보완, 단점은 데이터를 읽는 시간이 더 걸린다. 구현에 따라 Double LinkedList, Circular Double LinkedList가 있다.
ch11-15 Stack and Queue
Stack: LIFO 구조, 마지막 저장 제일 먼저 꺼낸다, push, pop 자바에서 Stakc이란 클래사가 있음
1 2 3 4 5 6 7
Stacks=newStack();
booleanempty(); Object pop(); // 비었을때는 EmptyStackException 발생 Object push(Object item); intsearch(Object o); // 못찾으면 -1, index가 1부터 시작 Object peek();
Queue: FIFO 구조, 제일 먼저 저장 제일 먼저 꺼낸다, offer, poll 자바에서 Queue는 인터페이스 이다. 구현체로 new 해야함, API 문서 보면 많은 구현체가 있음 (LinkedList, Abstract Queue, ArrayBlockingQueue, ArrayDeque, PriorityQueue 등등)
1 2 3 4 5 6 7 8 9 10
Queueq=newLinkedList();
booleanoffer(Object o); // 추가 booleanadd(Object o); // 저장 공간 부족하면 IllegalStateException 발생
Object poll(); // 꺼내기, 비어 있으면 null 반환 Object remove(); // 비어 있으면 NoSuchElementException 발생
Object peek(); // 비어 있으면 null 반환 Object element(); // peek 비어 있으면 NoSuchElementException 발생
ch11-19 스택과 큐 의 활용
스택: 수식계산, 수식괄호 검사, 워드프로세서의 undo/redo, 웹브라우저의 뒤로/앞으로 큐: 최근사용문서, 인쇄 작업 대기목록, 버퍼(buffer)
ch11-22~24 Iterator, ListIterator, Enumeration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicinterfaceCollection { //... public Iterator iteartor(); //... }
booleanhasNext(); // 읽어올 요소가 남아 있는지 확인 Object next(); // 다음 요소를 읽어 온다
SortedSet subSet(Object fromElement, Object toElement); // 범위 검색 SortedSet headSet(Object toElement); // 지정 된 객체보다 작은 것을 반환 SortedSet tailSet(Object fromElement); // 지정된 객체보다 큰것을 반환
ch11-46 HashMap과 Hashtable - 순서 X, 중복 (키X, 값O)
Map 인터페이스를 구현. 데이터를 키와 값의 쌍으로 저장
해시 함수(hash function)로 해시 테이블(Hash table)에 데이터를 저장, 검색
키(key) -> 해시함수(hash function) -> 해시코드(hash code) = 배열 index
// 동기화 버전 static Collection synchronizedCollection(Collection c); static List synchronizedList(List list); static Set synchronizedSet(Set s); static Map synchronizedMap(Map s); static SortedSet synchronizedSortedSet(SortedSet s);
ListsyncList= Collections.synchronizedList(newArrayList(...)); // 동기화 되지 않은
// 변경 불가 (readonly) 버전 static Collection unmodifiedCollection(Collection c); //....
// 싱글톤 컬렉션 만들기 static List singletonList(Object o); // 객체 1개만 저장 static Set singleton(Object o); static Map singletonMap(Object key, Object value);
// 한 종류의 객체만 저장 하는 컬렉션 만들기 static Collection checkedCollection(Collection c, Class type); static List checkedList(List list, Class type); static Set checkedSet(Set s, Class type); //....
Domain 패키지를 새로 만들고 안에 Entity와 Repository을 같이 작성 할 것이다. (더 공부 하려면 최범균 DDD Start 책을 참고 할수 있다고 한다.) Entity는 DB 테이블 이라고 보면 되고 클래스로 만들어 줘야 한다. Repository는 DB에 접근해주는기 위한 셋팅 이고 interface로 만들어 줘야 한다.
이런 설정은 원래 자바 코드 작성 해서 설정 할수 있으니 스프링 부트 에선 application.properties 나 application.yml 으로 설정 가능
spring.jpa.show_sql=true
1 2 3 4 5 6
Hibernate: createtable posts (id bigint generated bydefaultasidentity, author varchar(255), content TEXT notnull, title varchar(500) notnull, primary key (id))
Hibernate: insertinto posts (id, author, content, title) values (default, ?, ?, ?) Hibernate: select posts0_.id as id1_0_, posts0_.author as author2_0_, posts0_.content as content3_0_, posts0_.title as title4_0_ from posts posts0_ Hibernate: select posts0_.id as id1_0_, posts0_.author as author2_0_, posts0_.content as content3_0_, posts0_.title as title4_0_ from posts posts0_ Hibernate: deletefrom posts where id=?
@PostMapping("/api/v1/posts") public Long save(@RequestBody PostsSaveRequestDto requestDto) { return postsService.save(requestDto); }
@PutMapping("/api/v1/posts/{id}") public Long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto) { return postsService.update(id, requestDto); }
@DeleteMapping("/api/v1/posts/{id}") public Long delete(@PathVariable Long id) { postsService.delete(id); return id; }
@GetMapping("/api/v1/posts/{id}") public PostsResponseDto findById(@PathVariable Long id) { return postsService.findById(id); }
@GetMapping("/api/v1/posts/list") public List<PostsListResponseDto> findAll() { return postsService.findAllDesc(); }
publicfinalvoidwaits()throws InterruptedException { //... } /* Throws : 1. IllegalMonitorStateException 2. InterruptedException 함수 보면 Interrupted Exception 만 예외 선언 중이다. IllegalMonitorStateException은 RuntimeException의 자손임이다 (즉 예외처리가 선택적) */
ch8-14 finally 블럭
예외 발생 여부와 관계 없이 수행되어야 하는 코드를 넣는다
ch8-15 사용자 정의 예외 만들기
우리가 직접 정의 가능
조상은 Exception 과 RuntimeException 중 선택
1 2 3 4 5
classMyExceptionextendsException { MyException (String msg) { // 문자열을 매개변수로 받는 생성자 super(msg);// 조상인 Exception 클래스의 생성자를 호출 한다. } }
ch8-17 예외 되던지기 (exception re-throwing)
예외를 처리한 후에 다시 예외를 발생 시키는 것
호출한 메서드와 호출된 메서드 양쪽 모두에서 예외 처리 하는 것
catch 문 안에서 다시 throw e; 하면 된다.
ch8-18 연결된 예외 (chained exception)
한 예외가 다른 예외를 발생 시킬수 있다
예외 A가 예외 B를 발생 시키면, A는 B의 원인 예외 (cause exception)
1 2 3 4 5 6 7 8 9 10 11 12
Throwable initCause(Throwable cause) : 지정한 예외를 원인 예외로 등록 Throwable getCAuse() : 원인 예외를 반환
publicclassThrowableimplementsSerializable { // Exception과 Error 의 조상 클래스 //... privateThrowablecause=this; // 원인 예외를 저장 하기위한 iv //... publicsynchronized Throwable initCause(Throwable cause) { this.cause = cause; returnthis; } }
사용 예제 코드
1 2 3 4 5 6 7 8 9 10 11 12 13
voidinstall()throws InstallException {
try { startInstall(); copyFiles(); } catch (SpaceException e) { InstallExceptionie=newInstallException("설치 중 예외발생"); ie.initCause(e); // 원인을 새로 만든 예외에 넣고 throw ie; // 새로 만든 예외로 던짐 } catch (MemoryException me) { //... } }
사용 이유
여러 예외를 하나로 묶어서 다루기 위해서 (받는 쪽에서 너무 많은 Exception 종류 처리로 try catch 가 많은데 그걸 묶을수 있다.)
checked 예외를 unchecked예외로 변경 하려 할때
ch9 java.lang 패키지와 유용한 클래스
ch9-1 Object 클래스
모든 클래스의 최고 조상. 11개의 메서드 가지고 있음
notify(), wait()등은 쓰레드와 관련된 메서드 임
clone() : 복사
equals(Object obj) : 같은 객체 인지 확인
getClass() : 객체 자신의 클래스 정보를 담고 있는 Class 인스턴스를 반환
ch9-3 equals 의 오버라이딩
참조 변수로 확인 함으로 Class 안의 iv 값 비교 하기 위해서는 오버라이딩 해야 한다.
charcharAt(int index); // index 위치에 문자 반환 s.charAt(1);
intcompareTo(String str); // 문자열과 사전 순서로 비교, 0 같ㅇㅁ, 이전 음수, 이후 양수 inti1="aaa".compareTo("aaa"); // 0 inti2="aaa".compareTo("bbb"); // -1 // 왼쪽 작음 inti3="bbb".compareTo("aaa"); // 1 // 왼쪽 큼
오토박싱 10 -> new Integer(10) 언박싱 new Integer(10) -> 10
ch10-1 날짜와 시간
java.util.Date
날짜와 시간을 다룰 목적으로 만들어진 클래스 (JDK 1.0)
Date의 메서드는 거의 deprecated 되었음
java.util.Calendar
Data 클래스를 개선한 클래스 (JDK1.1)
java.time 패키지
Data 와 Calendar 의 단점을 개선한 새로운 클래스들을 제공 (JDK 1.8 -> Java 8)
날짜 + 시간, LocalDate, LocalTime, LocalDateTime
ch10-2 Calendar
추상 클래스 이므로 getInstance()을 통해 구현된 객체를 얻어야 한다.
1 2 3
Calendarcal=newCalendar(); // 생성 안됨, Calendar는 추상화 클래스 Calendarcal= Calendar.getInstance(); // 환경 변수를 참고 해서 생성 Calendarcal=newGregorianCalendar(); // 특정 Calendar의 생성
int get(int 필드값) 으로 날짜와 시간 필드 가져오기
주의: Month은 0 부터 시작
1 2 3
Calendarcal= Calendar.getInstance(); // 현재 날짜와 시간 intthisYear= cal.get(Calendar.YEAR); // 올해 가져오기 intlastDayOfMonth= cal.getActualMaximum(Calendar.DATE); // 이날의 마지막 날짜