Skip to content

아이템 17. 변경 가능성을 최소화하라 #37

Answered by JoisFe
jinan159 asked this question in 3. 과제
Discussion options

You must be logged in to vote

불변 클래스 정리 중

5) 자신 외에는 내부의 가변 컴포넌트에 접근할 수 없도록 한다.

에서 LocalDate 의 경우에는 return 문에서 항상 새로운 객체를 생성하여 반환 하여 자신 외에 내부의 가변 컴포넌트에 접근할 수 없도록 한 부분을 보다가 String 객체의 멤버 메서드의 return 또한 이러한 경우가 제법 있었던 것으로 기억났습니다.

String의 replace 메서드

 String str = new String("abc");
        str.replace("a", "z");

        System.out.println(str);

replace 메서드는 str 의 a를 z로 바꾸는 메서드 입니다. 결과를 보면

원하는 결과대로 이루어지 않고 원문 그대로 입니다.

 public String replace(CharSequence target, CharSequence replacement) {
        String tgtStr = target.toString();
        String replStr = replacement.toString();
        int j = indexOf(tgtStr);
        if (j < 0) {
            return this;
        }
        int tgtLen = tgtStr.length();
        int tgtLen1

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by jinan159
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
4장 클래스와 인터페이스 이펙티브 자바 4장 (클래스와 인터페이스)
4 participants