[Java] 유용한 클래스

iiueon·2023년 7월 13일

래퍼(wrapper) 클래스

래퍼(wrapper)클래스를 이용하면 기본형 값을 객체로 다룰 수 있다.

래퍼 클래스의 생성자

기본형래퍼클래스생성자
booleanBooleanBoolean (boolean value)
Boolean (String s)
charCharacterCharacter (char value)
byteByteByte (byte value)
Byte (String s)
shortShortShort (short value)
Short (String s)
intIntegerInteger (int value)
Integer (String s)
longLongLong (long value)
Long (String s)
floatFloatFloat (double value)
Float (float value)
Float (String s)
doubleDoubleDouble (double value)
Double (String s)

래퍼 클래스들은 equals(), toStinrg()이 오버라이딩되어 있다. 또한, 래퍼 클래스들은 MAX_VALUE, MIN_VALUE, SIZE, BYTES, TYPE 등의 static상수를 공통적으로 가지고 있다.

오토박싱 된다고 해도 Integer객체에 비교연산자를 사용할 수 없고, 대신 compareTo()를 제공한다.

Number클래스

추상클래스로 내부적으로 숫자를 멤버변수로 갖는 래퍼 클래스들의 조상

number class
기본형 중 숫자와 관련된 래퍼 클래스들은 모두 Number클래스의 자손이다. Number클래스 자손으로 BigInteger와 BigDecimal 등이 있는데, BigIntegerlong으로도 다룰 수 없는 큰 범위의 정수를, BigDecimaldouble로도 다룰 수 없는 큰 범위의 부동 소수점수를 처리하기 위한 것으로 연산자의 역할을 대신하는 다양한 메서드를 제공한다.

오토박싱 & 언박싱(autoboxing & unboxing)

오토박싱(autoboxing) : 기본형 값을 래퍼 클래스의 객체로 자동 변환해주는 것
언박싱(unboxing) : 래퍼클래스의 객체를 기본형 값으로 자동 변환해주는 것
	ArrayList<Integer> list = new ArrayList<integer>();
	list.add(10);            // (오토박싱) 10 -> new Integer(10)
    
	int value = list.get(0); // (언박싱) new Integer(10) -> 10 

java.util.Random클래스

💡 Math.random()을 이용한 메서드

  • 배열 arr을 from과 to범위의 값들로 채워서 반환한다.
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;
}
  • 배열 arr을 배열 data에 있는 값들로 채워서 반환한다
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;
}
  • from과 to범위의 정수(int)값을 반환한다. from과 to 모두 범위에 포함된다.
public static int getRand(int from, int to) {
    return (int)(Math.random() * (Math.abs(to - from) + 1))
    											+ Math.min(from, to);
}

정규식(Regular Expression) - java.util.regex패키지

정규식이란 텍스트 데이터 중에서 원하는 조건(패턴, pattern)과 일치하는 문자열을 찾아내기 위해 사용하는 것으로 미리 정의된 기호와 문자를 이용해서 작성한 문자열을 말한다.

정규식을 정의하고 데이터를 비교하는 과정

  1. 정규식을 매개변수로 Pattern클래스의 static메서드인 Pattern copmile(String regex)을 호출하여 Pattern인스턴스를 얻는다.
    Pattern p = Pattern.compile("c[a-z]*");
  2. 정규식으로 비교할 대상을 매개변수로 Pattern클래스의 Matcher matcher(CharSequence input)를 호출해서 Matcher인스턴스를 얻는다.
    Matcher m = p.matcher(data[i]);
  3. Matcher인스턴스에 boolean matches()를 호출해서 정규식에 부합하는지 확인한다.
    if(m.matches())



참고 자료

  • 자바의 정석 3판
profile
지연_로딩

0개의 댓글