Object클래스
- 모든 클래스의 최고 조상 오직 11개의 메서드만을 가지고 있다.
- notify(), wait()등은 쓰레드와 관련된 메서드다
- getClass()는 자동으로 만들어지며, 객체 자신의 클래스 정보를 담고있는 Class인스턴스를 반환한다(=객체정보==설계도 정보)

equals()
- 객체 자신(this)과 주어진 객체(obj)를 비교한다. 같으면 true 다르면 false
- Object클래스의 equals()는 객체의 주소를 비교(참조변수 값 비교)

- 따라서 equals() 의도대로 사용하고싶다면 오버라이딩 필수
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Ex9_1 { public static void main(String[] args) { Value v1 = new Value(10); Value v2 = new Value(10);
if (v1.equals(v2)) System.out.println("v1과 v2는 같습니다."); else System.out.println("v1과 v2는 다릅니다."); } }
class Value { int value;
Value(int value) { this.value = value; } public boolean equals(Object obj) { if (!(obj instanceof Value)) { return false; } Value v = (Value) obj; return this.value == v.value; } }
|
equals(Object obj)의 오버라이딩
- 인스턴스 변수(iv)의 값을 비교하도록 equals()를 오버라이딩해야한다.
- cv는 객체마다공통, iv는 객체마다다름

hashCode()
- 객체의 해시코드(hashCode())를 반환하는 메서드
- Object클래스의 hashCode()는 객체의 주소를 int로 변환해서 반환
객체의 주소를 int로 반환하여! 객체의 지문 역할함
네이티브(native) 메서드: OS의 메서드(C언어)
- equals()를 오버라이딩하면, hashCode()로 오버라이딩해야한다.
- 원래 둘다 주소를 가지고 판단함!!.
- iv를 가지고 판단원할경우 오버라이딩 둘다해야함
- equals()의 결과가 true인 두 객체의 해시코드는 같아야하기 때문이다.( 무조건 equals()와 hashCode() 결과는 같아야함. 무조건)
- System.identityHashCode(Object obj)
Object클래스의 hashCode()동일
객체마다 다른 해시코드 반환
toString(), to String()의 오버라이딩
- toString()
객체를 문자열(String)으로 변환하기 위한 메서드
- 원래의 toString()의 정의는 다음과같다

- 하지만 문자열에서 비교시 유용하지못하다.
- 객체는 iv의 모음인데,
객체를 문자열로 변환한다== iv를 문자열로 변환 개념이 더 자연스러움
- 따라서 다음과같이 toString오버라이딩

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import java.util.Objects;
class Card { String kind; int number;
Card() { this("SPADE", 1); }
Card(String kind, int number) { this.kind = kind; this.number = number; } public String toString() { return "kind:"+ kind +",number:"+number; } public boolean equals(Object obj) { if(!(obj instanceof Card)) return false; Card c = (Card)obj; return this.kind.equals(c.kind) && this.number == c.number; } public int hashCode() { return Objects.hash(kind, number); } }
class Ex9_4 { public static void main(String[] args) { Card c1 = new Card(); Card c2 = new Card();
System.out.println(c1.toString()); System.out.println(c2.toString()); System.out.println(c1.hashCode()); System.out.println(c2.hashCode()); if (c1.equals(c2)) System.out.println("오 같"); else System.out.println("오 틀리"); } }
|
- equals ()오버라이딩 하면 반드시 hashCode()도 결과동일하도록 오버라이딩해야함
String 클래스
- String클래스 = 데이터(char[])+ 메서드(문자열 관련)

- 내용을 변경할 수 없는 불변(immutable) 클래스
문자열 결합시, 새로운 객체가 만든후 가르키는 곳이 달라짐
- 새로운 객체를 만드는 경우 성능이 떨어짐!
- 문자열의 결합이나 변경이 잦다면, 내용을 변경가능한 StringBuffer를 사용

문자열의 비교
- String str = “abc”와 String str = new String(”abc”) 차이 비교

- String str1 = “abc”에서 리터럴 “abc”의 주소는 하나이며, 참조변수가 이 객체의 주소를 가짐.
- 문자열은 어차피 바꿀수없는 존재이므로 리터럴을 쓰는게 사용하는 객체가 늘어나지 않아좋다.
- new 연산자를 활용하면 항상 새로운 객체가 만들어짐
- 문자열은 비교시 항상 equals()를 활용하자(=iv를 비교!)
(’==’는 주소비교)
문자열 리터럴
- 문자열 리터럴은 프로그램 실행시 자동으로 생성된다.
(constant pool에 저장)(상수저장소)
- class는 원래 new를 해야하지만 String클래스는 특이함
- 같은 내용의 문자열 리터럴은 하나만 만들어진다.

빈 문자열(””,empty string)
- 내용이 없는 문자열. 크기가 0인 char형 배열을 저장하는 문자열
- 길이가 0인 배열을 생성하는 것은 어느 타입이나 가능
1 2
| char[] chArr = new char[0]; int[] iArr = {};
|
- 문자(char)와 문자열(String)의 초기화
초기화는 빈문자열, 공백으로 하자!

String클래스의 생성자와 메서드
String클래스의 생성자와 메서드(1/5)

String클래스의 생성자와 메서드(2/5)

String클래스의 생성자와 메서드(3/5)

String클래스의 생성자와 메서드(4/)

String클래스의 생성자와 메서드(5/5)

문자열, 기본형 변환
join()과 StringJoiner
- join()은 여러 문자열 사이에 구분자를 넣어서 결합한다.

숫자를 문자열로 바꾸는 방법

문자열을 숫자로 바꾸는 방법

종합
- 문자열 → 기본형 시 클래스 마다 valueof로 가능함. (new)

StringBuffer 클래스(문자열을 저장&다루기)
- String처럼 문자형 배열(char[])을 내부적으로 가지고 있다.

- 그러나, String과 달리 내용을 변경할 수 있다.(mutable)

- 배열은 길이 변경불가, 공간이 부족하면 새로운 배열 생성해야함(3단계)
- 새로운 배열 길이로 생성
- 내용 복사
- 참조 변경
- StringBuffer는 저장할 문자열의 길이를 고려해서 적절한 크기로 생성해야함

- append()는 StringBuffer로 반환함
- StringBuffer는 equals()가 오버라이딩되어있지않다. (>>주소비교함)
- StringBuffer를 String으로 변환 후에 equals()로 비교해야한다

StringBuffer의 생성자와 메서드(1/4)

StringBuffer의 생성자와 메서드(2/4)

StringBuffer의 생성자와 메서드(3/4)

StringBuffer의 생성자와 메서드(4/4)

예제

StringBuilder, Math클래스
StringBuilder
- StringBuilder는 동기화 X
- StringBuffer는 동기화 되어있다.
멀티 쓰레드에 안전(thread-safe)
싱글 쓰레드= 한번에 1개 작업
멀티 쓰레드= 한번에 n개 작업 >>데이터 공유됨>> 데이터 보호가 필요하다
- 멀티 쓰레드 프로그램이 아닌경우, 동기화는 불필요한 성능저하
이럴 땐 StringBuffer대신 StringBuilder를 사용하면 성능향상

Math클래스
- 수학관련 static메서드의 집합
- 상수는 두개 포함되어있다. E(자연로그 밑), PI(원주율)
- round()로 원하는 소수점 아래 세 번째 자리에서 반올림(사용법 숙지!!!)

Math클래스의 메서드(1/2)

Math클래스의 메서드(2/2)
- rint는 rounderen 은 짝수가 되도록 반올림종류중하나.
- round가 원래알고있는 흔한 반올림

래퍼클래스와 넘버 클래스
래퍼(wrapper) 클래스
- 8개의 기본형을 객체로 다뤄야할 때 사용하는 클래스
(=기본형값을 감싸는 클래스)


Number클래스

문자열을 숫자로 변환하기
- 문자열을 숫자로 변환하는 다양한 방법
- 래퍼클래스 >> intValue() >> 기본형 전환 가능!!! 꼭 확인하기
(intValue(), longValue() 이런형식으로 각 래퍼클래스에서 사용가능
- 다양한 방법!
(특히 래퍼클래스를 그대로 기본형 변수에 담아도바로 기본형으로 변환가능함)

- 만약 문자열로 모두 바꾸고 싶다면
String str = b.toString();
toString()활용하기
- n진법의 문자열을 (10진수)숫자로 변환하는 방법

오토박싱 & 언박싱
- int >>> Integer로 바꿔줌 오토박싱 (기본형 >>래퍼클래스)(자동)
- int <<< Integer 로 바꿔줌 언박싱 (기본형<<래퍼클래스)(자동)
- JDK 1.5이전에는 기본형과 참조형간의 연상이 불가능
- 언박싱 예시


- ArrayList에는 원래는 객체로만 넣어야함.. 하지만 이제는 기본형으로 써도 컴파일러가 자동으로 객체전환하여 넣어준다. 꺼낼때도 자동
- 아래와 같이 기본형과 참조형 간의 자동변환가능
(컴파일 전의 코드로 꼭활용하기)
(원칙적으로는 안되지만, 컴파일러가 오토박싱, 언박심 해줌)
