Skip to content

Latest commit

ย 

History

History
22 lines (17 loc) ยท 1.21 KB

Item_12._override_toString.md

File metadata and controls

22 lines (17 loc) ยท 1.21 KB

Item 12. toString์€ ํ•ญ์ƒ ์˜ค๋ฒ„๋ผ์ด๋”ฉํ•˜๋ผ

toString

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
  • Object ํด๋ž˜์Šค์˜ ๋ฉ”์„œ๋“œ ์ค‘ ํ•˜๋‚˜๋กœ, ํ•ด๋‹น ํด๋ž˜์Šค์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‹ด์€ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜
  • ๊ธฐ๋ณธ ๋™์ž‘์€ ์œ„์™€ ๊ฐ™์ด ํด๋ž˜์Šค๋ช…@16์ง„์ˆ˜ํ•ด์‹œ์ฝ”๋“œ๋ฅผ ๋ฐ˜ํ™˜
  • toString์˜ ๋ชฉ์ ์€ ๊ฐ„๊ฒฐํ•˜๊ณ  ์‚ฌ๋žŒ์ด ์ฝ๊ธฐ ์‰ฌ์šด ์ •๋ณด์˜ ์ œ๊ณต์ด์ง€๋งŒ, ์œ„ ํ˜•์‹์€ ์‚ฌ๋žŒ์ด ์ฝ๊ธฐ์— ์ข‹์€ ์ •๋ณด๊ฐ€ ์•„๋‹ ๋•Œ๊ฐ€ ๋งŽ๊ธฐ ๋•Œ๋ฌธ์— toString ๊ทœ์•ฝ์—์„œ๋Š” ์ด ๋ฉ”์„œ๋“œ๋ฅผ ์žฌ์ •์˜ํ•  ๊ฒƒ์„ ๊ถŒ์žฅํ•˜๊ณ  ์žˆ์Œ
    • ์šฐ๋ฆฌ๊ฐ€ ์•Œ๊ณ  ์‹ถ์€ ๊ฐ’์€ ๋Œ€๋ถ€๋ถ„ ๊ฐ์ฒด ๋‚ด ํ•„๋“œ์˜ ๊ตฌ์„ฑ์ด์ง€ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ๊ฐ’์ด ์•„๋‹˜

toString์„ ์˜ค๋ฒ„๋ผ์ด๋”ฉํ•  ๋•Œ์˜ ์œ ์˜ ์‚ฌํ•ญ

  • ํฌ๋งท์„ ๋ช…์‹œํ•ด ์˜ค๋ฒ„๋ผ์ด๋”ฉํ•˜๋Š” ๊ฒฝ์šฐ, ์ด ํฌ๋งท์„ ๋ฐ”๊พธ์ง€ ์•Š์•„์•ผ ํ•จ
    • ์ด ํฌ๋งท์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ฒฐ๊ณผ๊ฐ’์„ ํŒŒ์‹ฑํ•ด ์“ฐ๋Š” ๋ชจ๋“  ์ฝ”๋“œ๋“ค์ด ์œ ์ง€๋˜๊ธฐ ์œ„ํ•จ
  • Enum, Collections์™€ ๊ฐ™์€ ํด๋ž˜์Šค๋“ค์€ ์ด๋ฏธ ์ข‹์€ toString์„ ์ œ๊ณต
  • AutoValue, IDE ๋“ฑ์„ ํ†ตํ•ด ํšจ์œจ์ ์ธ toString์„ ์ž๋™์ƒ์„ฑํ•  ์ˆ˜ ์žˆ์Œ
    • ํ•˜์ง€๋งŒ ํŠน์ • ์ฒด๊ณ„๋ฅผ ๋”ฐ๋ผ์•ผ ํ•˜๋Š” toString์˜ ๊ฒฝ์šฐ ์ง์ ‘ ์ •์˜ํ•ด์•ผ ํ•จ