[220930] Wrapper 클래스, 지네릭

황준하·2022년 9월 30일
0

◆ String 클래스

▶ 자주 쓰이는 String 메소드 이어서

- StringBuffer와 StringBuilder

str3 = str + str2
syso str3
할당된 메모리가 모두 사용했을 때에, 그때 새롭게 여유분의 메모리를 추가로 할당하기 때문이다.

public class Test {

	
	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder("123");
		
		sb.append(4567);	//문자열 덧붙이기
		
		sb.delete(0, 2);	//문자열 삭제
		
		System.out.println(sb);
		sb.replace(0, 3, "AB");
		sb.reverse(); 	//문자열 뒤집기
		
		String sub = sb.substring(2, 4);
		
		System.out.println(sub);
		System.out.println(sb);
		System.out.println(sb.toString());

	}

}

▶실습문제

I Love you
Love youI
Love youI
ove youI L
ve youI Lo
e youI Lov
youI Love
youI Love
ouI Love y
uI Love yo
I Love you

public class Test {

	public static void main(String[] args) {
		String sb = new String("I Love you");
		String str;
		for (int i = 0; i <= sb.length(); i++) {
			System.out.println(sb);
			str = sb.substring(0, 1);
			sb = sb.substring(1);
			sb = sb + str;
		}

	}

}

- Math

package java_0930;

public class Test {

	public static void main(String[] args) {

		double radian45 = Math.toRadians(45);

		System.out.println("사인 45" + Math.asin(radian45));
		System.out.println("사인 45" + Math.cos(radian45));
		System.out.println("사인 45" + Math.tan(radian45));

		System.out.println("2의 16승: " + Math.pow(2, 16));
		System.out.println("로그 26: " + Math.log(25));

		System.out.println("랜덤 1~100: "+(int)(Math.random() * 100 + 1));
		
		System.out.println("파이: "+Math.PI);
	}

}

- Calendar

public class Test {

	public static void main(String[] args) {

		Calendar now = Calendar.getInstance();
		
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH);
		int date = now.get(Calendar.DATE);
		
		int hour12 = now.get(Calendar.HOUR);
		int hour24 = now.get(Calendar.HOUR_OF_DAY);
		int minute = now.get(Calendar.MINUTE);
		int second = now.get(Calendar.SECOND);
		
		int miliSecond = now.get(Calendar.MILLISECOND);
		int timeZone = now.get(Calendar.ZONE_OFFSET);
		int lastDay = now.getActualMaximum(Calendar.DATE);
		
		System.out.println(year +":"+month+":"+date);
		System.out.println(hour12+":"+hour24+":"+minute+":"+second+":"+miliSecond);
		System.out.println(timeZone+":"+lastDay);
	}

}

현재 시간은 11시 18분입니다.
Good Morning

public class Test {

	public static void main(String[] args) {

		Calendar now = Calendar.getInstance();
		
		int hour12 = now.get(Calendar.HOUR);
		int hour24 = now.get(Calendar.HOUR_OF_DAY);
		int minute = now.get(Calendar.MINUTE);
		
		System.out.println("현재 시간은 "+hour12+"시 "+minute+"분입니다.");
		if(hour24 >=4 && hour12  <= 12)
			System.out.println("Good Morning");
		else if(hour24 >12 && hour24 < 18)
			System.out.println("Good Evening");
		else
			System.out.println("Good Night");
	}

}

◆ Wrapper 클래스

- 언박싱 박싱 개념

int num = n1; // 언박싱
		System.out.println(num);

		Integer n3 = 5; // 박싱
		System.out.println(n3);
		
		int num1 =5;
		Integer num2 =5;
		//어떤게 더 좋은 방식일까? 1번

- int Integer 차이

		// n1과 n2는 객체
		// private final int value;

		Integer n1 = Integer.valueOf(5);
		Integer n2 = Integer.valueOf("1234");

- Integer 메소드

public class Test {

	public static void main(String[] args) {

		// n1과 n2는 객체
		// private final int value;

		Integer n1 = Integer.valueOf(5);
		Integer n2 = Integer.valueOf("1234");

		System.out.println("큰수 " + Integer.max(n1, n2));
		System.out.println("작은 수 " + Integer.min(n1, n2));
		System.out.println("합 : " + Integer.sum(n1, n2));

		System.out.println("2진 표현 " + Integer.toBinaryString(12));
		System.out.println("8진 표현 " + Integer.toOctalString(1000987));
		System.out.println("16진 표현 " + Integer.toHexString(12));

		System.out.println("정수의 최대값 " + Integer.MAX_VALUE);
		System.out.println("정수의 최소값" + Integer.MIN_VALUE);
	}

}

- BigInteger

		BigInteger big1 = new BigInteger("10000000000000000000000000");
		BigInteger big2 = new BigInteger("-9999999999999999999999990");
		
		BigInteger result = big1.add(big2);
		System.out.println("결과 "+ result);
		
		result = big1.multiply(big2);
		System.out.println("결과 " + result);

◆ 지네릭

▶ 지네릭 이해하기

1.5버전부터 시작됨

- 지네릭 이전 코드

package java_0930;

class Apple {

	@Override
	public String toString() {

		return "나는 사과";
	}
}

class Orange {

	@Override
	public String toString() {

		return "나는 오렌지";
	}
}

class Box {
	private Object obj;

	public void setObject(Object obj) {
		this.obj = obj;
	}

	public Object get() {
		return obj;
	}
}

public class Test {

	public static void main(String[] args) {

		Box aBox = new Box();
		Box oBox = new Box();

		aBox.setObject(new Apple());
		oBox.setObject(new Orange());

		Apple ap = (Apple) aBox.get();
		Orange og = (Orange) oBox.get();

		System.out.println(ap);
		System.out.println(og);
	}

}
  • 문제점 1
aBox.setObject("Apple");
oBox.setObject("Orange");

프로그래머의 실수로 new Apple()을 넣어줘야 하는데 "Apple"를 넣었다면?
객체를 받기 때문에 그대로 들어간다.
그러나 꺼내게 될때엔 클래스로 형변환 해주기 때문에 오류가 발생한다.

- 제네릭 기반의 클래스 정의하기

class Box<T> {
	private T obj;

	public void setObject(T obj) {
		this.obj = obj;
	}

	public T get() {
		return obj;
	}
}

public class Test {

	public static void main(String[] args) {

		Box<Apple> aBox = new Box<Apple>();
		Box<Orange> oBox = new Box<Orange>();

		aBox.setObject(new Apple());
		oBox.setObject(new Orange());

		Apple ap = aBox.get();	//형변환 하지 않는다.
		Orange og = oBox.get();	//형변환 하지 않는다.

		System.out.println(ap);
		System.out.println(og);
	}

}

- 제네릭

		Box<String> sBox = new Box<>();
		
		//sBox.setObject(new Orange()); //오류발생
		
		sBox.setObject("스트링");
		System.out.println(sBox.get());

실습문제

class DBox<S, I>{
	private S name;
	private I amount;
	
	public void set(S name, I amount) {
		this.name = name;
		this.amount = amount;
	}
	
	@Override
	public String toString() {
		return name + " & "+amount;
	}
}

public class Test {

	public static void main(String[] args) {

		DBox<String, Integer> box = new DBox<String, Integer>();
		box.set("Apple", 25);
		System.out.println(box);
	}

}

실습2

public class Test {
    public static void printArray(Object[] arr) {
        for (Object obj : arr) {
            System.out.println(obj);
        }
    }

    public static void main(String[] args) {
        Integer[] intArray = {1,2,3};
        String[] stringArray = {"Hello", "World"};
        printArray(intArray);
        printArray(stringArray);
    }
}

- 타입 인자 제한

lass Box<T extends Number> {
	private T obj;

	public void setObject(T obj) {
		this.obj = obj;
	}

	public T get() {
		return obj;
	}
}

public class Test {
   

    public static void main(String[] args) {
    	
    	Box<Integer> iBox = new Box<>();
    	iBox.setObject(24);
    	
    	System.out.println(iBox.get());
    	
    	//Box<Apple> aBox = new Box<>();	//type을 제한시켰기 때문에 오류발생
    }
}

- 제네릭 메소드의 정의

클래스가 전부가 아닌 메소드 하나에 대해 제네릭으로 정의

class Box<T> {
	private T obj;

	public void setObject(T obj) {
		this.obj = obj;
	}

	public T get() {
		return obj;
	}
}

class BoxFactory{
	public static <T> Box<T> makeBox(T o){
		Box<T> box = new Box<T>();
		box.setObject(o);
		return box;
	}
}
public class Test {
   

    public static void main(String[] args) {
    	
    	Box<String> sBox = BoxFactory.makeBox("Sweet");
    	System.out.println(sBox.get());
    	
    	Box<Double> dBox = BoxFactory.makeBox(7.59);
    	System.out.println(dBox.get());
    }
}

0개의 댓글