본문 바로가기

bitcamp/면접족보

면접족보 20/12/18_제네릭 개념

1. BigInteger 클래스 BigDecimal 클래스

· Biglnteger 클래스는 immutable의 속성을 지니며, 매우 큰 정수를 표현 할 때 사용한다.(long 이상의 수를 받아들일 때)
· BigDecimal 클래스는 실수를 표현 할 때 사용한다.

 

 

 

2. 아래의 결과 값은 false 출력이 된다. true가 되도록 INum을 작성하시오.

· 참고

 

· 작성 : 참고에서 Arrays equals(ar1, ar2)는 객체를 비교하기 때문에 서로 다른 인스턴스를 참조하고 있어 false를 출력한다.

  작성한 INum에서는 equals 함수 오버라이딩을 하여 단순히 내용을 비교하기 때문에 true를 출력하게 된다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 class INum{
    private int num;
    
    public INum(int num){
       this.num = num;
    }
    
    @Override
    public boolean equals(Object obj){
       if(this.num == ((INum)obj).num)
          return true;
       else
          return false;
    }
   
    public static void main(String[] args) {
      INum[] ar1 = new INum[3];
      INum[] ar2 = new INum[3];
      ar1[0= new INum(1); ar2[0= new INum(1);
      ar1[1= new INum(2); ar2[1= new INum(2);
      ar1[2= new INum(3); ar2[2= new INum(3);
      System.out.println(Arrays.equals(ar1, ar2)); 
    }
 }
cs

 

3. 아래의 내용을 참고하여 이름순으로 정렬되게 Person 객체를 작성하시오.

· 참고

 

· 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 class Person implements Comparable{
    private String name;
    private int age;
 
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Object o){
        Person p = (Person)o;
        return this.name.compareTo((p.name).name);
    }
    @Override
    public String toString() {
        return name + ": " + age;
    }    
 }
cs

 

 

4. 위의 문제에서 이름 글자수가 많은 순으로 정렬되게 person 객체를 작성하시오. 

· 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 class Person2 implements Comparable{
    private String name;
    private int age;
    
    public Person2(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Object o){
        Person2 p = (Person2)o;
        return p.name.length() - this.name.length();
    }
    @Override
    public String toString() {
        return name + ": " + age;
    }    
 }
cs

 

 

5. 다음 예시를 참고하여 경과시간을 맞추는 게임을 작성하시오.

· 참고: <Enter>키를 입력하면 현재 초 시간을 보여주고
         여기서 10초에 더 근접하도록 다음 <Enter> 키를 입력한 사람이 이기는 게임이다. 

 

· 작성

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
 class Game {
    private String name;
    private int result;
    
    Game(String name){
        this.name = name;
    }
    @Override
    public String toString() {
        return name;
    }
    public void getPlay() {
        Scanner sc = new Scanner(System.in);
        
        System.out.print(name + " 시작 키 >>");
        sc.nextLine();
        Calendar cal = Calendar.getInstance();
        int sec = cal.get(Calendar.SECOND);
        System.out.println("   현재 초 시간 = " + sec);
 
        System.out.print("10초 예상 후 키 >> ");
        sc.nextLine();
        Calendar cal2 = Calendar.getInstance();
        int sec2 = cal2.get(Calendar.SECOND);
        System.out.println("   현재 초 시간 = " + sec2);    
        
        if(sec2 >= sec) {
            result = sec2 - sec;
        }else{
            result = (sec2 + 60- sec;
        }    
        public int getResult() {    
            return result;
        }    
    }
 }
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 class Gamemain {
    public static void main(String[] args) {
        System.out.println("10초에 가까운 사람이 이기는 게임입니다.");
        Game user1 = new Game("황기태");
        Game user2 = new Game("이재문");
        user1.getPlay();
        user2.getPlay();
        
        System.out.println("황기태의 결과" + user1.getResult() + ", 이재문의 결과" + user2.getResult());
        if(user1.getResult() > user2.getResult()) {
            System.out.println("승자는 " + user2);
        }else if(user1.getResult() < user2.getResult()){
            System.out.println("승자는 " + user1);
        }else{
            System.out.println("무승부입니다.");
        }
    }
 }
cs

 

 

7. 제네릭이란?

· 최상위 클래스인 Object를 사용함으로써 모든 객체들을 받을 수 있기 때문에 컴파일 오류가 직접적(빨간줄)로 보이지 않고,

 실시간 에러(출력에서)를 발생시킨다.


· 가장 큰 문제는 실시간 오류가 발생하지않고, 전혀 다른 값을 출력하는 경우인데 이와 같은 문제점들을 보완하기 위해

  제네릭를 사용한다.
· 제네릭 타입을 이용함으로써 잘못된 타입이 사용되어 문제 발생 시 사전에 컴파일 과정에서 제거가 가능하고,
  객체의 타입을 컴파일 시에 체크하여 객체 타입의 안정성이 증가하고 형변환도 감소한다.
· 제네릭 타입은 < > 으로 표현하고, 그 사이에는 타입 파라미터를 가진다. 

 

 

8. 아래를 프로그래밍 하시오.

· 참고

 

· 작성

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
 class Rectangle{
    private int width;
    private int heigth;
 
    public Rectangle(int width, int heigth) {
            this.width = width;
            this.heigth = heigth;
    }    
    public int getHeight() {
            return heigth;
    }
    public void setHeight() {
            this.heigth = heigth;
    }
    public int getWidth() {
            return width;
    }
    public void setWeight() {
            this.width = width;
    }
    public static Rectangle compareRect(Rectangle r1, Rectangle r2) {
        if((r1.width < r2.width) && (r1.heigth < r2.heigth)){
            return r2;                    
        }else
            return r1;
    }
 }
cs

 

 

9. 아래를 프로그래밍 하시오. 

· 참고

 

· 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 class Rectangle implements Comparable{
    private int width;
    private int heigth;
 
    public Rectangle(int width, int heigth) {
        this.width = width;
        this.heigth = heigth;
    }    
    public int getArea() {
        return width * heigth;
    }
    @Override
    public int compareTo(Object o) {
        return this.getArea() - ((Rectangle2)o).getArea();
    }
    public String toString() {
        return  this.getArea() + ", ";
    }
 }
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 class Rectanglemain{
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        Rectangle[] rec = new Rectangle[4];
        for(int i = 0; i < rec.length; i++) {
            int w = sc.nextInt();
            int h = sc.nextInt();
            rec[i] = new Rectangle(w, h);
        }
        
        Arrays.sort(rec);
        for(Rectangle e : rec)
            System.out.print(e);
            System.out.println();
    }
 }
cs

 

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
class Rec {
    public static Rectangle[] getSortingRec(Rectangle[] recArr) {
        Rectangle[] rec = new Rectangle[4];
        Rectangle temp = null;
 
        if (rec instanceof Comparable[]) {
            for (int i = 0; i < rec.length; i++) {
                for (int j = 0; j < rec.length - i - 1; j++) {
                    if (rec[j].compareTo(rec[j + 1]) > 0) {
                        temp = rec[j];
                        rec[j] = rec[j + 1];
                        rec[j + 1= temp;
                    }
                }
            }
        } else {
            for (int i = 0; i < rec.length; i++) {
                for (int j = 0; j < rec.length - i - 1; j++) {
                    if (rec[j].getArea() > rec[j + 1].getArea()) {
                        temp = rec[j];
                        rec[j] = rec[j + 1];
                        rec[j + 1= temp;
                    }
                }
            }
        }
        return rec;
    }
}
cs