Back-End

[JAVA] 기초공부 11 제네릭과 컬렉션

Minch13r 2025. 1. 20. 17:39

2025.1.20 자바 제네릭과 컬렉션

 

[예외처리]

오류 났을 때 캡쳐 → 에러원인 작성(0으로 나누기를 수행해서 발생한 에러) → 해결방안 작성(0으로 나누기를 수행해서는 안됨)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

예외

코드가 예상과 다른 라인에서 멈춰버리는 현상

프로그램이 갑자기 종료되버리는 현상

사용자 경험 저하

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

예외처리

오류를 해결하는 것이 아니라, 프로그램을 정상적으로 종료할 수 있게 혹은 프로그램을 끝까지 사용할 수 있게 코딩

빨간 글씨를 사용자가 볼 수 없게 코딩


instance of 없으면 Circle이 아닌 애들 에러 남. 원이 아니면 equals 자체가 아니라는거를 증명

먼저 전처리를 해주는거임

if(!(obj instanceof Circle)){ return false; } → 먼저 전처리

 

묵시적 형변환 / 강제 형변환 존재

묵시적 double d = 3; 작은 타입에서 큰 타입으로 갈 때 일어남

강제 int i = (int)3.14; // 강제 형변환은 앞에 소괄호()가 일어남

data loss가 일어남, 주로 큰 타입에서 작은 타입으로 갈 때 일어남

캐스팅

업 포켓몬 p = 피카츄객체;

다운 피카츄 p = (피카츄)포켓몬객체;

package day014.class03;

/*
리스트에 1~10까지의 랜덤정수를 5개 저장해주세요.
단, 값 중복없이 해주세요.
사용자에게 정수를 1개 입력받아, 해당자리의 값을 0으로 변경합니다.

1. 컬렉션을 활용해 문제를 풀어주세요
2. 예외처리를 해주세요.
*/

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class Test02 {
    public static void main(String[] args) {
        ArrayList<Integer> datas = new ArrayList<>();

        // 랜덤 객체 생성
        Random rand = new Random();
        // 스캐너 객체 생성
        Scanner sc = new Scanner(System.in);

        // 1~10까지의 숫자를 리스트에 추가
        while(datas.size() < 5) { // 크기 5
            int num = rand.nextInt(10) + 1; // 1~10
            if(!datas.contains(num)) { // 중복 체크
                datas.add(num); // 랜덤 생성된 숫자 추가
            }
        }
        // 현재 리스트 출력
        System.out.println("현재 리스트 : " + datas);

        while(true) { // 언제 제대로 입력될지 몰라서 무한루프
            try {
                System.out.print("인덱스 번호를 입력해주세요 : ");
                int a = sc.nextInt();
                datas.set(a, 0); // 해당 인덱스의 값을 0으로 변경
                System.out.println("변경된 리스트 : " + datas);
                break;
            } catch (InputMismatchException e) {
                System.out.println("올바른 인덱스 번호를 입력해주세요!");
                continue;
            } catch (IndexOutOfBoundsException e){
                System.out.println("올바른 인덱스 번호를 입력해주세요!");
                continue;
            } catch (Exception e){
                System.out.println("올바른 인덱스 번호를 입력해주세요!");
                continue;
            }
        }
    }
}

package day014.class04;

/*
 * 원을 생성하기 위해서는 이름과 반지름이 반드시 필요합니다.
 * 캡슐화를 수행해주세요.
 * 원 객체를 3개 생성하여 리스트에 저장해주세요
 * 리스트에서 가장 넓이가 큰 원의 이름을 출력해주세요.
 * 단, 원의 넓이가 나중에 저장된 원이 출력되도록 해주세요
 *
 * +++) 원 객체들은 이름이 같다면 반지름이 달라도 같은 객체로 인정
 * 이름을 사용자에게 입력받아, 같은 객체의 개수를 세어 출력해주세요(오버라이딩 사용)
 * */

import java.util.ArrayList;

// 캡슐화는 private로 진행, 생성자, getter, setter 만들기
// 파이는 상수화 하고 생성자엣서 넓이는 반지름^2 * PI로 진행
class Circle {
    private String name;
    private int radius;
    private double area;
    private static final double PI = 3.14;

    //생성자
    Circle(String name, int radius){
        this.name = name;
        this.radius = radius;
        this.area = this.radius * this.radius * PI;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getRadius() {
        return radius;
    }
    public void setRadius(int radius) {
        this.radius = radius;
        this.area = PI * radius * radius;
    }

    public double getArea() {
        return area;
    }
    public void setArea(double area) {
        this.area = area;
    }

    @Override
    public String toString() {
        return "Circle{" +
                "name='" + name + '\'' +
                ", radius=" + radius +
                ", area=" + area +
                '}';
    }
}

public class Test01 {
    public static void main(String[] args) {
        /*원 생성한거 받을 리스트 생성
         * 원 3개 생성
         * 가장 큰 넓이를 가진 원 기본값 설정
         * 넓이 계산해서 가장 넓이가 큰 원 찾고 이름 출력
         * 원의 넓이가 똑같을 때, 인덱스 뒤에 번호꺼를 출력
         * 뒤에서부터 검사하면 될 것 같음.*/

        // 원 받을 리스트 생성, 제네릭은 Circle로 지정
        ArrayList<Circle> datas = new ArrayList<>();

        // 원 이름과 반지름 길이 다르게 해서 생성
        datas.add(new Circle("A", 5));
        datas.add(new Circle("B", 9)); // B와 C 반지름 같게 설정
        datas.add(new Circle("C", 9));

        Circle maxArea = datas.get(0); //기본값 설정

        // datas.size()로 크기 설정하고 -1까지 해서 우리가 원하는 수로 지정
        // 넓이가 동일했을 때 나중에 저장된 원이 출력되도록 하는데, for문으로 돌리다 보면
        // 넓이가 동일해도 나중에 있는게 저장돼서 나옴
        for(int i = 0; i <= datas.size()-1; i++){
            if(datas.get(i).getArea() >= maxArea.getArea()) { // 넓이가 기본값보다 크면
                maxArea = datas.get(i); // 치환
            }
        }
        System.out.println("가장 큰 원의 이름: " + maxArea.getName()); // 가장 큰 원 이름 불러오기

    }
}

 

 

Set은 중복을 허용하지 않고 순서가 존재하지 않는다. 그래서 중복방지를 할 때 이제 set을 사용하면 중복되지 않는다.

package day014.class06;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class Test02 {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<Integer>();

        Random rand = new Random();
        while(true){
            int randNum =rand.nextInt(10);
            set.add(randNum);
            if(set.size()>=5){
                break;
            }
        }
        System.out.println(set);
    }
}

 

Map은 key와 value가 한쌍으로 진행되는데 key는 중복이 허용 안 되고 value는 허용된다. 제네릭 할 때 한쌍으로 진행

package day014.class06;

import java.util.HashMap;
import java.util.Map;

// 맵 Map
// key : value
// Key 값은 중복을 허용하지 않는다 --->> 유일한 값.
// value는 중복이 허용된다. 동명이인이 있을 수 있다는 느낌
// python으로 따지면 dictionary와 같은 느낌
public class Test03 {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();

        map.put(101, "사과");
        map.put(102, "바나나");
        map.put(103, "키위");

        System.out.println(map);
    }
}

package day014.class07;

/*class Point
   int x
   int y
class ColorPoint extends Point
   String color

Point() ▶ (0,0)
Point(1,2) ▶ (1,2)
ColorPoint() ▶ 검정(0,0)
ColorPoint(1,2) ▶ 검정(1,2)
ColorPoint(분홍) ▶ 분홍(0,0)
ColorPoint(1,2,분홍) ▶ 분홍(1,2)

모든 점 객체들을 저장할 수 있는 리스트에 임의로 10개의 점 객체들을 저장해주세요.

점들은 좌표가 같다면 같은 점으로 판단합니다.

[0]에 저장된 점과 같은 점은 몇개인지 출력해주세요.

색을 사용자에게 입력받아서
같은 색의 점이 몇개 존재하는지 출력해주세요.

+++) 이 문제를 map 을 활용해서 해결해주세요.
점들에게 번호를 1001번부터 순차적으로 부여합니다.
*/


import java.util.*;

/*
* Point 클래스 생성, 멤버변수 x,y 설정
* 생성자 인자 두개 다 있는거랑 없는거 오버로딩 진행
*/
class Point {
    int x;
    int y;

    Point() {
        this(0, 0);
    }

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point{" + "x=" + x + ", y=" + y + '}';
    }
}

/* colorPoint 클래스 생성, 멤버변수 color 설정
 * 생성자 인자 여러개 오버로딩 해야 할 것 같음 상황에 맞게*/
class ColorPoint extends Point {
    String color;

    public ColorPoint(int x, int y, String color) {
        super(x, y);
        this.color = color;
    }

    public ColorPoint() {
        this(0, 0, "검정");
    }
    public ColorPoint(int x, int y) {
        this(x, y, "검정");
    }
    public ColorPoint(String color) {
        this(0, 0, color);
    }

    public void setColor(String color) {
        this.color = color;
    }
    public String getColor() {
        return color;
    }

    @Override
    public String toString() {
        return "ColorPoint{" + "color='" + color + '\'' + '}';
    }
}

/*
* Point 클래스 관련 리스트 선언
* HashMap으로 번호랑 포인트 매핑
* 임의의 점 10개 만들고 Arraylist랑 HashMap에 저장
* [0]에 저장된 점과 같은 점 몇개인지 찾아야 함
* get(0)으로 기본값 세팅하고 equals 써서 똑같은 점 찾고
* 변수 따로 둬서 찾을 때마다 카운트 한개씩 올려서 카운트 수 출력
* 색깔은 scanner로 색 입력받아서 위에랑 같이 equals 써서 찾기*/
public class Test01 {
    public static void main(String[] args) {
        // Point 클래스 관련 리스트
        ArrayList<Point> points = new ArrayList<>();

        // 번호랑 점 매핑
        Map<Integer, Point> map = new HashMap<>();

        // 10개의 점 임의로 생성 및 저장
        points.add(new Point(0, 0));
        points.add(new ColorPoint(1, 2, "분홍"));
        points.add(new Point(0, 0));
        points.add(new ColorPoint(3, 4, "파랑"));
        points.add(new ColorPoint(0, 0, "검정"));
        points.add(new ColorPoint(5, 6, "분홍"));
        points.add(new Point(3, 8));
        points.add(new ColorPoint(9, 10, "파랑"));
        points.add(new Point(1, 9));
        points.add(new ColorPoint(7, 3, "분홍"));

        // Map에 점들 저장 (1001번부터 번호 부여)
        for (int i = 0; i < points.size(); i++) {
            map.put(1001 + i, points.get(i));
        }

        // [0]에 저장된 점과 같은 점 개수 찾기
        // 지정 안 됨 issue
        Point point = points.get(0);
        int cnt = 0; // 카운트 0으로 초기화
        for (Point p : points) {
            if (p.equals(point)) { // firstPoint와 같은 점 찾을 때마다
                cnt++; // 카운트 개수 1개씩 증가
            }
        }
        
        System.out.println("[0]에 저장된 점과 같은 좌표를 가진 점의 개수: " + cnt);

        // 스캐너 객체 생성
        Scanner scanner = new Scanner(System.in);
        System.out.print("찾고 싶은 색상을 입력하세요: ");
        // 스캐너로 색상 입력받기
        String color = scanner.nextLine();

        // 같은색 카운트 변수
        int pointCnt = 0;
        for (Point p : points) {
            try {
                //point 타입으로는 getColor를 쓸 수 없어서
                // 기존 Point 타입의 p를 ColorPoint로 형변환
                ColorPoint cp = (ColorPoint) p;  // 형변환
                if (cp.getColor().equals(color)) { // 같은거 찾으면
                    pointCnt++; // 카운트 향상
                }
            } catch (Exception e) {
                continue;  // 가독성 향상
            }
        }
        System.out.println("입력한 색상을 가진 점의 개수: " + pointCnt);

//        for(int i=0; i<points.size(); i++) {
//            System.out.println(points.get(i));
//        }
    }
}

좌표 비교가 안돼서 equals 다시 오버라이딩 하고 진행하니까 잘 됐다.

package day014.class07;

/*class Point
   int x
   int y
class ColorPoint extends Point
   String color

Point() ▶ (0,0)
Point(1,2) ▶ (1,2)
ColorPoint() ▶ 검정(0,0)
ColorPoint(1,2) ▶ 검정(1,2)
ColorPoint(분홍) ▶ 분홍(0,0)
ColorPoint(1,2,분홍) ▶ 분홍(1,2)

모든 점 객체들을 저장할 수 있는 리스트에 임의로 10개의 점 객체들을 저장해주세요.

점들은 좌표가 같다면 같은 점으로 판단합니다.

[0]에 저장된 점과 같은 점은 몇개인지 출력해주세요.

색을 사용자에게 입력받아서
같은 색의 점이 몇개 존재하는지 출력해주세요.

+++) 이 문제를 map 을 활용해서 해결해주세요.
점들에게 번호를 1001번부터 순차적으로 부여합니다.
*/


import java.util.*;

/*
* Point 클래스 생성, 멤버변수 x,y 설정
* 생성자 인자 두개 다 있는거랑 없는거 오버로딩 진행
*/
class Point {
    int x;
    int y;

    Point() {
        this(0, 0);
    }

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point{" + "x=" + x + ", y=" + y + '}';
    }

    @Override
    public boolean equals(Object obj) {  // Object 타입의 매개변수
        // 자기 자신과 비교할 때
        if (this == obj) {
            return true;
        }
        // null이거나 다른 클래스인 경우
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        // Point로 형변환
        Point point = (Point) obj;
        // x와 y 좌표가 모두 같은지 비교
        return x == point.x && y == point.y;
    }
}

/* colorPoint 클래스 생성, 멤버변수 color 설정
 * 생성자 인자 여러개 오버로딩 해야 할 것 같음 상황에 맞게*/
class ColorPoint extends Point {
    String color;

    public ColorPoint(int x, int y, String color) {
        super(x, y);
        this.color = color;
    }

    public ColorPoint() {
        this(0, 0, "검정");
    }
    public ColorPoint(int x, int y) {
        this(x, y, "검정");
    }
    public ColorPoint(String color) {
        this(0, 0, color);
    }

    public void setColor(String color) {
        this.color = color;
    }
    public String getColor() {
        return color;
    }

    @Override
    public String toString() {
        return "ColorPoint{" + "color='" + color + '\'' + '}';
    }
}

/*
* Point 클래스 관련 리스트 선언
* HashMap으로 번호랑 포인트 매핑
* 임의의 점 10개 만들고 Arraylist랑 HashMap에 저장
* [0]에 저장된 점과 같은 점 몇개인지 찾아야 함
* get(0)으로 기본값 세팅하고 equals 써서 똑같은 점 찾고
* 변수 따로 둬서 찾을 때마다 카운트 한개씩 올려서 카운트 수 출력
* 색깔은 scanner로 색 입력받아서 위에랑 같이 equals 써서 찾기*/
public class Test01 {
    public static void main(String[] args) {
        // Point 클래스 관련 리스트
        ArrayList<Point> points = new ArrayList<>();

        // 번호랑 점 매핑
        Map<Integer, Point> map = new HashMap<>();

        // 10개의 점 임의로 생성 및 저장
        points.add(new Point(0, 0));
        points.add(new ColorPoint(1, 2, "분홍"));
        points.add(new Point(0, 0));
        points.add(new ColorPoint(3, 4, "파랑"));
        points.add(new ColorPoint(0, 0, "검정"));
        points.add(new ColorPoint(5, 6, "분홍"));
        points.add(new Point(3, 8));
        points.add(new ColorPoint(9, 10, "파랑"));
        points.add(new Point(1, 9));
        points.add(new ColorPoint(7, 3, "분홍"));

        // Map에 점들 저장 (1001번부터 번호 부여)
        for (int i = 0; i < points.size(); i++) {
            map.put(1001 + i, points.get(i));
        }

        // [0]에 저장된 점과 같은 점 개수 찾기
        // 지정 안 됨 issue
        Point point = points.get(0);
        int cnt = 0; // 카운트 0으로 초기화
        for (Point p : points) {
            if (p.equals(point)) { // point와 같은 점 찾을 때마다
                cnt++; // 카운트 개수 1개씩 증가
            }
        }
        System.out.println("[0]에 저장된 점과 같은 좌표를 가진 점의 개수: " + cnt);

        // 스캐너 객체 생성
        Scanner scanner = new Scanner(System.in);
        System.out.print("찾고 싶은 색상을 입력하세요: ");
        // 스캐너로 색상 입력받기
        String color = scanner.nextLine();

        // 같은색 카운트 변수
        int pointCnt = 0;
        for (Point p : points) {
            try {
                //point 타입으로는 getColor를 쓸 수 없어서
                // 기존 Point 타입의 p를 ColorPoint로 형변환
                ColorPoint cp = (ColorPoint) p;  // 형변환
                if (cp.getColor().equals(color)) { // 같은거 찾으면
                    pointCnt++; // 카운트 향상
                }
            } catch (Exception e) {
                continue;  // 가독성 향상
            }
        }
        System.out.println("입력한 색상을 가진 점의 개수: " + pointCnt);
    }
}

좌표 비교가 안돼서 equals 다시 오버라이딩 하고 진행하니까 잘 됐다.

'Back-End' 카테고리의 다른 글

[JAVA] 기초 공부 13 MVC  (1) 2025.01.22
[JAVA] 기초 공부 12 File I/O  (2) 2025.01.21
[JAVA] 3중 상속과 인터페이스  (4) 2025.01.17
[JAVA] 기초 공부 10  (1) 2025.01.15
[JAVA] 기초 공부 9  (1) 2025.01.14