item 26 leekyunghee - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki
List ์ธํฐํ์ด์ค๋ ์์์ ํ์ ์ ๋ํ๋ด๋ ํ์ ๋งค๊ฐ๋ณ์ E๋ฅผ ๋ฐ๋๋ค. ์ธํฐํ์ด์ค์ ์์ ํ ์ด๋ฆ์ List์ง๋ง ์งง๊ฒ ๊ทธ๋ฅ List ๋ผ๊ณ ๋ ์์ฃผ์ด๋ค.
- ์ ๋ค๋ฆญ ํ์ ์ ์ผ๋ จ์ ๋งค๊ฐ๋ณ์ํ ํ์ ์ ์ ์ํ๋ค. (ํด๋์ค/์ธํฐํ์ด์ค ์ด๋ฆ + <ํ์ >)
- Raw type์ด๋ List์ Raw ํ์ ์ List๋ค.
- Raw type์ ํ์ ์ ์ธ์์ ์ ๋ค๋ฆญ ํ์ ์ ๋ณด๊ฐ ์ ๋ถ ์ง์์ง ๊ฒ์ฒ๋ผ ๋์ํ๋๋ฐ ์ ๋ค๋ฆญ์ด ๋๋ํ๊ธฐ ์ ์ฝ๋์ ํธํ๋๋๋ก ํ๊ธฐ ์ํ ๊ถ์ฌ์ง์ฑ ์ด๋ผ ํ ์ ์๋ค.
- Raw type๋ ํจ๊ป ์ ์๋๋ค.
[before] ์ปฌ๋ ์
์ Raw ํ์
- ๋ฐ๋ผํ์ง ๋ง ๊ฒ!
private final Collection stamps = ...;
// ์ด ์ฝ๋๋ฅผ ์ฌ์ฉํ๋ฉด ์ค์๋ก ๋์ฅ(Stamp) ๋์ ๋์ (Coin)์ ๋ฃ์ด๋ ์๋ฌด ์ค๋ฅ ์์ด ์ปดํ์ผ๋๊ณ ์คํ๋๋ค.(์ปดํ์ผ๋ฌ๊ฐ ๋ชจํธํ ๊ฒฝ๊ณ ๋ฉ์์ง๋ฅผ ๋ณด์ฌ์ฃผ๊ธด ํ ๊ฒ์ด๋ค.)
stamps.add(new Coin(...)); // "unchecked call" ๊ฒฝ๊ณ ๋ฅผ ๋ด๋ฑ๋๋ค.
์ปฌ๋ ์
์์ ์ด ๋์ ์ ๋ค์ ๊บผ๋ด๊ธฐ ์ ์๋ ์ค๋ฅ๋ฅผ ์์์ฑ์ง ๋ชปํ๋ค.
[before] ๋ฐ๋ณต์์ ๋ก ํ์
- ๋ฐ๋ผํ์ง ๋ง ๊ฒ!
for (Iterator i = stamps.iterator(); i.hasNext();) {
Stamp stamp = (Stamp) i.next(); // ClassCastException ์ ๋์ง๋ค.
stamp.cancel();
}
[after] ๋งค๊ฐ๋ณ์ํ๋ ์ปฌ๋ ์
ํ์
- ํ์
์์ ์ฑ ํ๋ณด
private final Collection<Stamp> stamps = ...;
// ์ปดํ์ผ๋ฌ๊ฐ ์ธ์งํ๊ฒ ๋จ
// ์ปดํ์ผ๋ฌ๋ ์ปฌ๋ ์
์์ ์์๋ฅผ ๊บผ๋ด๋ ๋ชจ๋ ๊ณณ์ ๋ณด์ด์ง ์๋ ํ๋ณํ์ ์ถ๊ฐํ์ฌ ์ ๋ ์คํจํ์ง ์์์ ๋ณด์ฅํ๋ค.
Test.java:9: error: incompatible types: Coin cannot be converted to Stamp
stamp.add(new Coin());
// Stamp์ฉ ์ปฌ๋ ์
์ Coin์ ๋ฃ๋๋ค๋ ์์
// ์๋ฅผ ๋ค์ด BigDecimal์ฉ ์ปฌ๋ ์
์ BigInteger๋ฅผ ๋ฃ๋ ์ค์๋ ๊ทธ๋ฆฌ ์ต์ง ๊ฐ์ง ์์ ๊ฒ
// ๋กํ์
(ํ์
๋งค๊ฐ๋ณ์๊ฐ ์๋ ์ ๋ค๋ฆญ ํ์
)์ ์ฐ๋ ๊ฑธ ์ธ์ด ์ฐจ์์์ ๋ง์ ๋์ง๋ ์์์ง๋ง ์ ๋๋ก ์จ์๋ ์๋๋ค.
// ๋ก ํ์
์ ์ฐ๋ฉด ์ ๋ค๋ฆญ์ด ์๊ฒจ์ฃผ๋ ์์ ์ฑ๊ณผ ํํ๋ ฅ์ ๋ชจ๋ ์๊ฒ ๋๋ค.
List๊ฐ์ Raw ํ์ ์ ์ฌ์ฉํด์๋ ์๋๋ List ์ฒ๋ผ ์์ ๊ฐ์ฒด๋ฅผ ํ์ฉํ๋ ๋งค๊ฐ๋ณ์ํ ํ์ ์
- Raw ํ์ ์ธ List์ ๋งค๊ฐ๋ณ์ํ ํ์ ์ List์ ์ฐจ์ด
List๋ ์ ๋ค๋ฆญ ํ์ ์์ ์์ ํ ๋ฐ์ ๋บ ๊ฒ์ด๊ณ List๋ ๋ชจ๋ ํ์ ์ ํ์ฉํ๋ค๋ ์์ฌ๋ฅผ ์ปดํ์ผ๋ฌ์ ๋ช ํํ ์ ๋ฌ
๋งค๊ฐ๋ณ์๋ก List๋ฅผ ๋ฐ๋ ๋ฉ์๋์ List์ ๋๊ธธ ์ ์์ง๋ง List๋ฅผ ๋ฐ๋ ๋ฉ์๋์๋ ๋๊ธธ ์ ์๋ค.
List์ Raw ํ์ ์ธ List์ ํ์ ํ์ ์ด์ง๋ง List์ ํ์ ํ์ ์ ์๋๋ค.
// ์ฝ๋ 26-4 ๋ฐํ์์ ์คํจํ๋ค. - unsafeAdd ๋ฉ์๋๊ฐ Raw ํ์
(List)์ ์ฌ์ฉ
public class Raw {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
unsafeAdd(strings, Integer.valueOf(42));
String s = strings.get(0); // ์ปดํ์ผ๋ฌ๊ฐ ์๋์ผ๋ก ํ๋ณํ ์ฝ๋๋ฅผ ๋ฃ์ด์ค๋ค.
}
private static void unsafeAdd(List list, Object o) {
list.add(o); // [unchecked] call to add(E) as member of the raw type List
}
}
ํต์ฌ ์ ๋ฆฌ
Raw ํ์
์ ์ฌ์ฉํ๋ฉด ๋ฐํ์์ ์์ธ๊ฐ ์ผ์ด๋ ์ ์์ผ๋ ์ฌ์ฉํ๋ฉด ์๋๋ค.
Set<Object>์ Set<?>์ ์์ ํ์ง๋ง ๋ก ํ์
์ธ Set์ ์์ ํ์ง ์๋ค.