가장 기본이 되는 클래스들(import문 없이도 사용 가능)
cf. reflection API : 동적 객체 생성/ 메서드 호출
오버라이딩할 때 조상 메서드의 반환타입을 자손 클래스의 타입으로 변경을 허용
ex)
public Point clone() { // 반환타입을 Object에서 Point로 변경
Object obj = null;
try {
obj = super.clone();
} catch(CloneNotSupportedException e) {}
return (Point)obj; // Point타입으로 형변환한다.
}
: Point copy = (Point)original.clone();
-> Point copy = original.clone()
clone()
: 객체의 값을 단순 복제(=얕은 복사) -> 객체가 참조하기 있는 객체까지 복제x
문자열 저장 : char[] value
-> 한번 생성된 String 인스턴스가 갖고 있는 문자열은 읽어 올 수만 있고,변경할 수는 없다.
StringBuffer
클래스(문자열 변경 가능)컴파일시에 클래스 파일에 저장됨(String 인스턴스)
💡parseInt()
: 주로 trim()
과 함께 쓰임(문자열 양끝의 공백 제거 후 변환)
https://docs.oracle.com/javase/7/docs/api/
*보충문자 : 유니코드는 원래 2 byte, 즉 16비트 문자체계인데, 이걸로도 모자라서 20비트로 확장하게 되면서 추가된 문자들 -> 하나의 문자를 char타입으로 다루지 못하고, int타입으로 다룰 수밖에 없다.
StringBuffer
: 멀티쓰레드에 안전(thread safe)하도록 동기화 되어 있음
-> 성능이 떨어짐
-> 쓰레드의 동기화만 뺀 것 : StringBuilder
(나머지는 동일)
Exact
가 포함된 메서드들(addExact
, subtractExact
...) : 오버플로우 발생시 예외 발생시킴기본형 값들을 객체로 다루기 위해 사용
new Integer(문자열).intValue(); //floatValue(), longValue(),...
Integer.parseInt(문자열);
: 주로 이 방법 많이 사용Integer.valueOf(문자열)
-> 오토박싱
기능 때문에 구별없이 valueOf()
사용해도 괜찮음(성능은 조금 느래다
<-> 기본형과 참조형간의 연산이 불가능 : 래퍼클래스로 기본형을 객체로 만들어 연산 수행
모든 메서드가 static
Object 클래스의 메서드와 이름이 같은 것들은 클래스의 이름을 붙여줘야 함
isNull()
, nonNull()
, requireNonNull()
void setName(String name) {
this.name = Objects.requireNonNull(name, "name must not be null.");
}
equals()
, deepEquals()
equals()
: Object 클래스의 equals()
와 달리 따로 널 검사 필요x, 객체 둘다 null이면 true 리턴deepEquals()
: 다차원 배열의 배교 가능(2차원 문자열, ..)public static int[] fillRand(int[] arr, int from, int to) {
for (int i = 0; i < arr.length; i++)
arr[i] = getRand(from, to);
return arr;
}
public static int[] fillRand(int[] arr, int[] data) {
for (int i = 0; i < arr.length; i++)
arr[i] = data(getRand(0, data.length - 1));
return arr;
}
public static int getRand(int from, int to) {
return (int)(Math.random() * (Math.abs(to - from) + 1)) +
Math.min(from, to);
}
정규식 : 원하는 조건(패턴, pattern)과 일치하는 문자열을 찾아내기 위해 사용하는 것
Pattern compile(String regex)
을 호출하여 Pattern인스턴스를 얻는다.Pattern p = Pattern.compile("c[a-z]★");
Matcher matcher (CharSequence input)
를 호출해서 Matcher인스턴스를 얻는다.Matcher m = p.matcher(data[i]);
matches()
if(m.matches())
find()
: 주어진 소스 내에서 패턴과 일치하는 부분을 찾아내면 true를 반환
Matcher
의 find()
로 정규식과 일치하는 부분을 찾으면, 그 위치를 start()
와 end()
로 알 아 낼 수 있고 appendReplacement(StringBuffer sb, String replacement)
를 이용해서 원하는 문자열(replacement)로 치환할 수 있다
import java.util.regex.*; // Pattern과 Matcher가 속한 패키지
class RegularEx4 {
public static void main(String[] args) {
String source = "A broken hand works, but not a broken heart.";
String pattern = "broken";
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(source);
System.out.printIn("source: " + source);
int i = 0;
while (m.find()) {
System.out.printIn(++i + "HM OS:" + m.start() + "~" + m.end());
// broken을 drunken으로 치환하여 Sb에 저장한다.
m.appendReplacement(sb, "drunken");
}
m.appendTail(sb);
System.out.printIn("Replacement count : " + i);
System.out.printIn("result:" + sb.toString());
}
}
입력을 받기위한 메서드들 : nextInt()
, nextLine()
...
긴 문자열을 지정된 구분자(delimiter)를 기준으로 여러 개의 문자열(토큰 token)로 잘라내는 데 사용(구분자가 한글자인 경우에만 사용 가능)
String - split(String regex)
, Scanner - useDelimiter(String patter)
: 같은 용도, 정규식을 사용해야 함
1001||200|30
1001|200|30
import java.util.*;
class StringTokenizerEx2{
public static void main (String[] args) {
String expression = "×=100* (200+300) /2";
StringTokenizer st = new StringTokenizer(expression, "+-*/=()", true); // 구분자 : '+', '-', '*', '/', '=','(', '),
while (st.hasMoreTokens ()) {
System.out.println(st.nextToken());
}
} // main의 끝
long 타입 : 약 까지 표현 가능,
그 이상 : BigInteger
Biglnteger val;
val = new Biglnteger ("12345678901234567890"); // 문자열로 생성
val = new Biglnteger(’FFFF", 16); // n진수(radix)의 문자열로 생성
val = Biglnteger.valueOf(1234567890L); // 숫자로 생성
String toString() // 문자열로 변환
String toString(int radix) // 지정된 진법 (radix)의 문자열로 변환
byte[] toByteArray() // byte배열로 변환
int intValue()
long longValue()
float floatValue()
double doubleValue()
byte byteValueExact()
int intValueExact()
long longValueExact()
(1) 사칙 연산
Biglnteger add(Biglnteger val)
// this + val
Biglnteger subtract(Biglnteger val)
// this - val
Biglnteger multiply(Biglnteger val)
// this * val
Biglnteger divide(Biglnteger val)
// this / val
Biglnteger remainder(Biglnteger val)
// this % val
(2) 비트 연산 : 워낙 큰 숫자를 다루기 위한 클래스이므로, 성능을 향상시키기 위해
int bitCount ()
//2진수로 표현했을 때, 1의 개수 (음수는 0의 개수) 를 반환int bitLength ()
//2진수로 표현했을 때, 값을 표현하는데 필요한 bit수boolean testBit (int n)
// 우측에서 n+1번째(n은 0부터 시작) 비트가 10면 true, 00면 falseBigInteger setBit (int n)
//우측에서 n+1번째 비트를 1로 변경BigInteger clearBit (int n)
// 우측에서 n+1번째 비트를 0으로 변경BigInteger flipBit (int n)
//우측에서 n+1번째 비트를 전환 (10, 0-1)BigInteger처럼 불변(immutable)
정수를 이용해서 실수를 표현 :
BigDecimal val;
val = new BigDecimal ("123. 4567890"); // 문자열로 생성
val = new BigDecimal (123.456); //double타입의 리터럴로 생성
val = new BigDecimal (123456); //int, 1ong타입의 리터럴로 생성가능
val = BigDecimal.value0f (123.456) ; //생성자 대신 valueof (double) 사용
val = BigDecimal.value0f (123456); //생성자 대신 valueof (int) 사용
*double 타입의 값을 매개변수로 갖는 생성자는 오차가 발생할 수 있음
System.out.println(new BigDecimal(0.1));// 0.10000000000000000555111...
System.out.println(new BigDecimal("0.1")); // 0.1
String toPlainString() //어떤 경우에도 다른 기호없이 숫자로만 표현
String toString () //필요하면 지수형태로 표현할 수도 있음
int intValue()
long longValue ()
float floatValue ()
double doubleValue ()
byte byteValueExact ()
short shortValueExact()
int intValueExact ()
long longValueExact()
BigInteger toBigIntegerExact()
메서드
BigDecimal divide(BigDecimal divisor)
BigDecimal divide(BigDecimal divisor, int roundingMode)
BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode)
BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
BigDecimal divide(BigDecimal divisor, MathContext me)
*나눗셈한 결과가 무한소수인 경우, 반올림 모드를 지정해주지 않으면 ArithmeticException 발생
반올림모드와 정밀도를 하나로 묶어 놓은 것
I think it is good bike race