Java/[국비] JAVA

[국비][JAVA] 코드 분석_메모리 영역을 통한 이해_예시(2)

줌인. 2024. 6. 6. 11:34

▶ 메모리 영역_예시를 통한 이해(1)

https://zoooom-in.tistory.com/119

 

[국비][JAVA] 메모리 영역_예시를 통한 이해(1) 및 NullPointerException 예제 보기

▶ 자바 메모리 영역https://zoooom-in.tistory.com/103 [국비][JAVA] 자바 메모리 영역▶ 참고 (자바 메모리와 static 구조)https://zoooom-in.tistory.com/57 [김영한_자바기본][7. 자바 메모리 구조와 static] 자바 메모

zoooom-in.tistory.com

 

[예제 코드_WeatherDTO]

public class WeatherDTO {
    private String city;
    private double gion;
    private String status;
    private int humidity;

    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public double getGion() {
        return gion;
    }
    public void setGion(double gion) {
        this.gion = gion;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public int getHumidity() {
        return humidity;
    }
    public void setHumidity(int humidity) {
        this.humidity = humidity;
    }
}

 

[예제 코드_WeatherService]

public class WeatherService {
    private StringBuffer sb;

    public WeatherService() {
        this.sb = new StringBuffer();
        this.sb.append("서울 , 29.3 - 맑음 - 60");
        this.sb.append("- 부산 , 33.6 - 흐림 - 90");
        this.sb.append("- 제주 , 26.5 - 눈 - 30");
        this.sb.append("- 광주 , 10.6 - 태풍 - 80");
    }

    public WeatherDTO[] init() {
        String info = this.sb.toString(); //StringBuffer -> String type으로 변환
        info = info.replace(",", "-"); //StringBuffer에 들어갔던 ","을 "-"로 변환
        WeatherDTO [] dtos = this.getWeathers(info);
        return dtos;
    }

    private WeatherDTO [] getWeathers(String info) {//초기StringBuffer에 있던 내용 16개
        //16개를 기반으로 배열 생성할 것.
        String [] infos = info.split("-"); 
        int idx = 0;
        WeatherDTO [] dtos = new WeatherDTO[infos.length / 4]; //16개 중 4씩 나눠서 배열에 담고 싶음
        //배열이 있으면 배열안에 객체가 있어야 함
        //dtos[0].getCity()를_dtos 0번째에 있는 겟 시티에 접근한다를 하면 nullPointerException이 뜸
        //이유는 dtos 배열 선언만 한 상태, 초기화가 되어있지 않음. 즉 null 상태
        //dtos[0] == null, 즉 null에 접근하면 데이터를 확보할 수 없다.

        for(int i = 0; i < dtos.length ; i++ ) {
            WeatherDTO w = new WeatherDTO(); //객체생성 
            //따라서 WeatherDTO[] 배열이기에 WeatherDTO 타입을 가진 객체를 주면, 객체의 세부 주소에 접근 가능하다.
            w.setCity(infos[idx++].trim());
            w.setGion(Double.parseDouble(infos[idx++].trim()));
            w.setStatus(infos[idx++].trim());
            w.setHumidity(Integer.parseInt(infos[idx++].trim()));
            dtos[i] = w;
        }
        return dtos; //값을 넣은 배열 반환
    }
}

 

[예제 코드_WeatherView]

public class WeatherView { //담은 결과물 출력 코드 작성하기
    //메서드 이름 view
    //View class에서는 객체 생성없이 view로 출력하게 할 것임
    //매개변수로 WeatherView의 배열 전체를 받아와서 배열 내역을 출력해야 함
    public void view(WeatherDTO[] dtos) {
        for(int i=0; i<dtos.length;i++) {
            System.out.println(dtos[i].getCity());
            System.out.println(dtos[i].getGion());
            System.out.println(dtos[i].getStatus());
            System.out.println(dtos[i].getHumidity());
            System.out.println("==========");
        }
    }
}

 

 

[예제 코드_WeatherController]

public class WeatherController {
    //초기 값 선언되지 않았기 떄문에 모두 null;
    private WeatherDTO[] dtos; //weather 정보 데이터를 모아둔 곳
    //weatherService에 init을 실행하면 배열을 반환하기 때문에 해당 내역을 반환 받아서 넣는다.
    private WeatherService weatherService; //weather 정보 데이터 생성
    private WeatherView weatherview; //weather 정보 출력 할 곳

    //상기 코드의 초기화는 내부 생성자에서 진행
    public WeatherController() {
        this.weatherview = new WeatherView();
        this.weatherService = new WeatherService();
        this.dtos = weatherService.init();
    }

    //1. 날짜 정보 출력 2. 종료
    //메서드명 start();
    public void start() {
        Scanner sc = new Scanner(System.in);
        boolean flag = true;
        while(flag) {
            System.out.println("1. 날씨 정보 출력 // 2.종료");
            int option = sc.nextInt();
            if(option == 1) { //1번을 누르면 날씨 전체 정보 출력
                this.weatherview.view(dtos); // weatherView에 view메서드를 출력하면 전체 정보 출력
            } else if(option == 2) {
                System.out.println("종료");
                flag = false;
            }
        }
    }
}

 

[WeatherService 메모리 생성 구조 도식화]

 

- 리턴받지 못하는 값은 사라지며, 리턴받는 값을 변수에 담으면 메서드가 사라짐에도 불구하고 재사용할 수 있음

- 배열 자체를 생성할 경우 초기값을 대입하지 않았기 때문에 null이 발생

- 객체에 특정 요소에 접근하고 싶을 경우는 객체 생성이 이루어져야 함

 

 

  • Controller에 대한 주소값과 참조값 더 알아보기
    • WeatherController는 WeatherDTO 배열과 WeatherService, WeatherView 객체를 참조
    • 참조값이란 해당 객체의 메모리 주소를 가리키는 값으로, 객체 자체가 아니라 객체가 저장된 메모리 주소 저장
    • this.dtos = weatherService.init();에서 dtos는 weatherService.init() 메서드가 반환한 WeatherDTO 배열의 참조값을 저장. 이 참조값을 통해 dtos는 배열에 저장된 각 객체에 접근할 수 있음
    • WeatherService에서 배열을 생성하면 이 배열의 주소값이 반환
    • WeatherController에서 이 주소값을 받아 dtos에 저장하여 동일한 객체 배열에 접근할 수 있음

 

728x90