JiwonDev

3-4 Cloneable์„ ์‚ฌ์šฉํ•˜์ง€ ๋งˆ๋ผ & Comparable์˜ ์‚ฌ์šฉ

by JiwonDev

# Cloneable์„ ์‚ฌ์šฉํ•˜์ง€ ๋งˆ๋ผ.

Cloneable์€ ์–ด๋–ค ๊ฐ์ฒด๊ฐ€ ๋ณต์ œ(clone)์„ ํ—ˆ์šฉํ•œ๋‹ค๋Š” ์‚ฌ์‹ค์„ ์•Œ๋ฆฌ๋Š” ๋ฐ ์“ฐ๋ ค๊ณ  ๊ณ ์•ˆ๋œ ๋ฏน์Šค์ธ(mixin) ์ธํ„ฐํŽ˜์ด์Šค๋‹ค.

์ด ์ธํ„ฐํŽ˜์ด์Šค์—๋Š” clone ๋ฉ”์„œ๋“œ๊ฐ€ ์—†์œผ๋ฉฐ, Object์˜ clone ๋ฉ”์„œ๋“œ๋Š” protected๋กœ ์„ ์–ธ๋˜์–ด ์žˆ๋‹ค.

 

๋‹ค๋งŒ ๋ฐฐ์—ด์„ ์ œ์™ธํ•˜๊ณ , ์ผ๋ฐ˜์ ์ธ ์ž๋ฐ” ๊ฐ์ฒด์— ์‚ฌ์šฉํ•˜๋Š”๊ฑด ๋ถˆ๊ฐ€๋Šฅํ•œ ์ผ์ด๋‹ค. ์‚ฌ์šฉํ•˜์ง€ ๋ง์ž.

 

๋‹จ์ˆœํžˆ super.clone()์ด ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฐ์ฒด๋ฅผ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๊ตฌํ˜„ํ•œ๋‹ค๋ฉด ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ๋‹ค.

clone ๋ฉ”์„œ๋“œ๋Š” ๋˜ ๋‹ค๋ฅธ ํ˜•ํƒœ์˜ ์ƒ์„ฑ์ž์ด๋‹ค. ์›๋ž˜ ๊ฐ์ฒด๋ฅผ ์†์ƒ์‹œํ‚ค๋Š” ์ผ์ด ์—†๋„๋ก ํ•ด์•ผ ํ•˜๊ณ , ๋ณต์‚ฌ๋ณธ์˜ ๋ถˆ๋ณ€์‹(invariant)๋„ ์ œ๋Œ€๋กœ ๋งŒ์กฑ์‹œ์ผœ์•ผ ํ•œ๋‹ค. Stack์˜ clone ๋ฉ”์„œ๋“œ๊ฐ€ ์ œ๋Œ€๋กœ ๋™์ž‘ํ•˜๋„๋ก ํ•˜๋ ค๋ฉด ์Šคํƒ์˜ ๋‚ด๋ถ€ ๊ตฌ์กฐ๋„ ๋ณต์‚ฌํ•ด์•ผ ํ•œ๋‹ค.

 

clone ๋ฉ”์„œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์€ ๋ณต์žกํ•œ ๊ณผ์ •์ด๋‹ค. clone ๋ฉ”์„œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•ด์•ผ๋งŒ ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ๋ฉด, ๊ฐ์ฒด๋ฅผ ๋ณต์‚ฌํ•  ๋Œ€์•ˆ์„ ์ œ๊ณตํ•˜๊ฑฐ๋‚˜, ์•„์˜ˆ ๋ณต์ œ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ด ๋‚ซ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋ณ€๊ฒฝ ๋ถˆ๊ฐ€๋Šฅ ํด๋ž˜์Šค๋Š” ๊ฐ์ฒด ๋ณต์ œ๋ฅผ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ด ๋งž๋‹ค. ๋ณต์‚ฌ๋ณธ์€ ์›๋ž˜ ๊ฐ์ฒด์™€ ๋…ผ๋ฆฌ์ ์œผ๋กœ ๊ตฌ๋ณ„์ด ๋ถˆ๊ฐ€๋Šฅํ•  ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ.

@Override public Stack clone() {
    try {
        Stack result = (Stack) super.clone();
        result.elements = elements.clone();
        return result;
    } catch (CloneNotSupportedException e) {
        throw new AssertionError();
    }
}

 

 

# sort ๊ธฐ๋Šฅ์„ ๋งŒ๋“ค๋ ค๊ณ  ํ•œ๋‹ค๋ฉด Comparable ๊ตฌํ˜„๋„ ๊ณ ๋ คํ•˜๋ผ.

sort ๊ธฐ๋Šฅ์„ ๋งŒ๋“ค๋ ค๊ณ  ํ•œ๋‹ค๋ฉด Comparable์„ ๊ตฌํ˜„ํ•˜๊ณ  ์‚ฌ์šฉํ•˜์ž.

๋ฐ•์‹ฑ๋œ ๊ธฐ๋ณธํƒ€์ž… ํด๋ž˜์Šค (Integer)์˜ ๊ฒฝ์šฐ, static compare๋‚˜ Comparator ์ธํ„ฐํŽ˜์ด์Šค๊ฐ€ ์ œ๊ณตํ•˜๋Š” ๋น„๊ต์ž (Comparator) ์ƒ์„ฑ ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•˜๋ฉด ์ข‹๋‹ค.

 

์ด๋ ‡๊ฒŒ ํ•˜๋Š” ์ด์œ ๋Š” Comparable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๋ฉด Collection๊ณผ ์—ฐ๋™ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋˜ํ•œ Comparable์€ ์ œ๋„ค๋ฆญ์„ ์ธํ„ฐํŽ˜์ด์Šค์ด๋ฏ€๋กœ ์ปดํŒŒ์ผ ์‹œ๊ฐ„์— ํƒ€์ž…๊ฒ€์ฆ์ด ์™„๋ฃŒ๋˜๊ธฐ์—, ๋น„๊ตํ•˜๋Š” ํ•จ์ˆ˜์—์„œ ์ธ์ž๋กœ ๋ฐ›์€ ๊ฐ์ฒด์˜ ์ž๋ฃŒํ˜•์„ ๊ฒ€์‚ฌํ•˜๊ฑฐ๋‚˜ (myClass) value ์ฒ˜๋Ÿผ ๋ถˆํ•„์š”ํ•œ ์บ์ŠคํŒ…์„ ํ•  ํ•„์š”๋„ ์—†์–ด์ง„๋‹ค.  

 dogs.sort(Dog.getReversedComparator());
@ToString
@Builder
@Getter
public class Dog {

    private final static Comparator<Dog> reversedComparator =
            Comparator.comparingInt(Dog::getAge)
                    .thenComparingInt(Dog::getLegs)
                    .reversed();

    public static Comparator<Dog> getReversedComparator() {
        return reversedComparator;
    }

    private int age;
    private int legs;
}

 

๋ธ”๋กœ๊ทธ์˜ ์ •๋ณด

JiwonDev

JiwonDev

ํ™œ๋™ํ•˜๊ธฐ