쉽지않은 블로그
[JAVA] 자바의 String 본문
자바에서 String 은 C++ 에서 다루던것과 많이 다른느낌이여서 처음 사용할때 많은 혼란을 주었다.
str[3] 이게 왜 안됨???
JAVA 의 String 에 대해서 정리하고자 이 글을 쓴다.
String 클래스는 java.base jar 파일의 java.lang에 담겨있다.
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** * The value is used for character storage. * * @implNote This field is trusted by the VM, and is a subject to * constant folding if String instance is constant. Overwriting this * field after construction will cause problems. * * Additionally, it is marked with {@link Stable} to trust the contents * of the array. No other facility in JDK provides this functionality (yet). * {@link Stable} is safe here, because value is never null. */ @Stable private final byte[] value; /** * The identifier of the encoding used to encode the bytes in * {@code value}. The supported values in this implementation are * * LATIN1 * UTF16 * * @implNote This field is trusted by the VM, and is a subject to * constant folding if String instance is constant. Overwriting this * field after construction will cause problems. */
쉽게 생각하면 String 의 char 의 배열이라고 생각할수 있다
소스코드에는 byte 라고는 나와있지만 (byte : 1byte char : 2byte)
한글도 표현가능한걸 봐선 유니코드일경우 char로 변환하여 잘 저장하지 않을까 싶다.
String 클래스의 선언부에 CharSequence 인터페이스를 구현한다고 나와있는데
CharSequence 란 문자열을 편하게 다뤄주기 위한 표준규격이다
구현체들 : CharBuffer , Segment , String, StringBuffer , StringBuilder 등이 있다.
많이 사용하는 메소드
char charAt(int i) | 문자열의 i번째 문자를 반환한다 //str[i] 는 안되요.... |
String (char [] value) | 생성자로 char 형 배열을 입력받을 수 있다 |
int compareTo (String str) | 사전순으로 비교한다 ex) A.compareTo(B) //A와 B는 String 형 을 할경우 양수이면 A가 B보다 뒤에 있고 음수일경우 A가 B보다 앞에 있다. //쉽게 A-B라고 생각 |
String concat(String str); | 문자열을 합친후 새로운 String 반환 |
int indexOf(char a); int indexOf(String b); |
해당문자열또는 문자가 시작하는 인덱스를 반환 존재하지 않을 경우 -1 반환 |
String[] split(String regex); | regex 패턴을 기준으로 문자열을 분리하여 문자열 배열을 반환 |
char[] toCharArray() | 문자열을 char형 배열로 반환한다. |
String str = "abc" 와 String str = new String("abc") 의 차이
String a = "abc"; String b = "abc"; System.out.println(a==b); // true System.out.println(a.equals(b)) // true String c = new String("aaa"); String d = new String("aaa"); System.out.println(c==d); // false System.out.println(c.equals(d)) // true
hashCode값을 찍어보면 같다고 나오지만 new 연산자를 이용하여 생성할경우
c , d 는 "aaa" 를 가르키는 (C에서 포인터) 구조로 생기게 된다
그래서 a 는 b와 같다고 판별하지만 c 와 d는 다르다고 판단하게 된다.
이러한 이유때문에 객체를 비교할때는 무조건
equals 메소드를 이용하여 비교해주어야 한다. equals 는 Object 클래스의 메소드이다
String 의 경우 이미 구현이 되어있기 때문에 바로 사용해주어도 되지만
사용자정의 클래스일 경우 인스턴스 내부 값들을 다비교해주는 equals 메소드를 오버라이드 해주어야 한다.
'프로그래밍언어 > JAVA' 카테고리의 다른 글
[JAVA] Object 클래스 (0) | 2021.04.14 |
---|---|
[JAVA] Wrapper class 래퍼클래스란? (2) | 2021.04.13 |
[JAVA] 제네릭 이란? (0) | 2021.03.31 |
[JAVA] 컬렉션 이란? (0) | 2021.03.31 |