{TIL} 0218

2021. 2. 18. 21:39ใ†๐Ÿ“” TIL

 

 

1. Java Optional.ofNullable()

Optional<Member> member = Optional.ofNullable(aMember);
Optional<Member> noMember = Optional.ofNullable(null);

์ž๋ฐ”๋Š” NullPointerException (NPE) ์—๋Ÿฌ๋ฅผ ์œ ๋ฐœํ•˜๊ธฐ ์‰ฝ๋‹ค.

๊ทธ๋Ÿฐ ์ƒํ™ฉ์„ ๋ชจ๋ฉดํ•˜๊ธฐ ์œ„ํ•ด if๋ถ„๊ธฐ๋ฌธ์œผ๋กœ ์‚ฌ์ „์— ์˜ˆ๋ฐฉํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, Optional.ofNullable() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ null pointer exception์„ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค. ์œ„์˜ ์ฝ”๋“œ์—์„œ๋Š” aMember๊ฐ€ null์ด ๋  ์ˆ˜ ์žˆ๋Š” ๋ณ€์ˆ˜๊ฐ€ ๋œ๋‹ค.

 

2. Java ArrayList vs Array

ArrayList<String>  language = new ArrayList<String> (); // new ArrayList<>() ๋„ ๊ฐ€๋Šฅ

language.add("korean");
System.out.println(language.toString());
language.add("english");
System.out.println(language.toString());
language.add("chinese");
System.out.println(language.toString());

>>> ["korean", "english", "chinese"]

ArrayList๋Š” Array๋ณด๋‹ค ์ถ”๊ฐ€๋œ ๊ธฐ๋Šฅ์ด ๋งŽ๋‹ค. ์œ„์˜ add (python์œผ๋กœ ์น˜๋ฉด append) ๋ฉ”์†Œ๋“œ๋Š” array์—์„  ์•ˆ๋˜์ง€๋งŒ, ArrayList์—์„  ๊ฐ€๋Šฅํ•˜๋‹ค.

 

์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉด, ๋ฐฐ์—ด์€ ์ดˆ๊ธฐ ๊ฐ’์„ ๋ฏธ๋ฆฌ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฆ‰ ๋ฐฐ์—ด ์„ ์–ธ ๋‹จ๊ณ„์—์„œ ๊ฐ’์˜ ์ •์˜๊นŒ์ง€ ๊ฐ€๋Šฅํ•˜๋‹ค.

๋ฆฌ์ŠคํŠธ๋Š” ์ด๋Ÿฌํ•œ ์ ์ด ๊ฐ€๋Šฅํ•˜์ง€ ์•Š์ง€๋งŒ, add(), remove()๋“ฑ ๋ฆฌ์ŠคํŠธ ๋‚ด ์›์†Œ๋ฅผ ์ž์œ ๋กญ๊ฒŒ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋Š” ๋‹ค์–‘ํ•œ ๋ฉ”์†Œ๋“œ๊ฐ€ ์กด์žฌํ•œ๋‹ค.

// Array, ๋ฐฐ์—ด
String[] weeks = {"์›”", "ํ™”", "์ˆ˜", "๋ชฉ", "๊ธˆ", "ํ† ", "์ผ"};

// List, ๋ฆฌ์ŠคํŠธ
ArrayList pitches = new ArrayList();
pitches.add("138");
pitches.add("129");
pitches.add("142");


์ถœ์ฒ˜: ์ ํ”„ ํˆฌ ์ž๋ฐ”

'๐Ÿ“” TIL' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

TIL 210506  (0) 2021.05.06
{TIL} 210221  (0) 2021.02.21
{TIL} 0208  (0) 2021.02.08
{TIL} 0204  (0) 2021.02.04
{TIL} 0201 Object.assign()  (0) 2021.02.02