[Java] ArrayList(add, get, remove, size, contains)

epiphanyยท2022๋…„ 11์›” 4์ผ
0

Programmers School

๋ชฉ๋ก ๋ณด๊ธฐ
20/22
post-thumbnail

๐Ÿ›ซ Programmers School ๋ฌธ์ œ ํ’€์ด ๊ณผ์ •์—์„œ ์•Œ๊ฒŒ ๋œ ๊ฐœ๋… ์ •๋ฆฌ

ArrayList

๐Ÿงฉ ArrayList ํŠน์ง•

  • ์ผ๋ฐ˜์  ๋ฐฐ์—ด์€ ํฌ๊ธฐ๊ฐ€ ๊ณ ์ •์ ์ด์ง€๋งŒ ArrayList๋Š” ํฌ๊ธฐ๊ฐ€ ๊ฐ€๋ณ€์ 
  • ์ธ๋ฑ์Šค๋Š” ๋™์ผํ•˜๊ฒŒ 0๋ถ€ํ„ฐ ์‹œ์ž‘
  • ์—ฐ์†๋œ ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„ ์‚ฌ์šฉ

๐Ÿงฉ ArrayList ์ƒ์„ฑ ๋ฐฉ๋ฒ•

import java.util.ArrayList;

ArrayList<Integer> arr = new ArrayList<Integer>();
ArrayList<Integer> arr = new ArrayList<>();
ArrayList<Integer> arr = new ArrayList<>(20);
  • ArrayList<์ƒ์„ฑํ•  ํƒ€์ž…> ๋ฐฐ์—ด๋ช… = new ArrayList<์ƒ์„ฑํ•  ํƒ€์ž…>(์ดˆ๊ธฐ์— ์„ค์ •ํ•  ์šฉ๋Ÿ‰);
  • new ๋‹ค์Œ์— ์˜ค๋Š” ์ƒ์„ฑํ•  ํƒ€์ž…์€ ์ƒ๋Ÿ‰ ๊ฐ€๋Šฅ

๐Ÿงฉ add()

๋ฐฐ์—ด์— ๊ฐ’ ์ถ”๊ฐ€ํ•˜๊ธฐ

String s = "apple";
ArrayList<String> arr = new ArrayList<>();

arr.add(s);
arr.add("banana");

๐Ÿงฉ get()

๋ฐฐ์—ด ๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ

String s = "apple";
ArrayList<String> arr = new ArrayList<>();

arr.add(s);
arr.add("banana");

arr.get(0); // apple

๐Ÿงฉ remove()

๋ฐฐ์—ด ๊ฐ’ ์‚ญ์ œํ•˜๊ธฐ
index, value๋กœ ์‚ญ์ œํ•  ์ˆ˜ ์žˆ์Œ

String s = "apple";
ArrayList<String> arr = new ArrayList<>();

arr.add(s);
arr.add("banana");

arr.remove(0); // apple ์‚ญ์ œ
arr.remove("banana"); // banana ์‚ญ์ œ

๐Ÿงฉ size()

๋ฐฐ์—ด์˜ ํฌ๊ธฐ ๊ฐ€์ ธ์˜ค๊ธฐ

String s = "apple";
ArrayList<String> arr = new ArrayList<>();

arr.add(s);
arr.add("banana");

arr.size(); // 2

๐Ÿงฉ contains()

๋ฐฐ์—ด์— ๊ฐ’์ด ํฌํ•จ๋˜์—ˆ๋Š”์ง€ ํ™•์ธ

String s = "apple";
ArrayList<String> arr = new ArrayList<>();

arr.add(s);
arr.add("banana");

arr.contains("banana"); // true
arr.contains("peach"); // false

๐Ÿ“š Reference

0๊ฐœ์˜ ๋Œ“๊ธ€