1. 콜렉션
- 자바는 내부적으로 여러 개의 같은 데이터 타입의 객체들을 한꺼번에 모아서 제어할 수 있는 "Collection"이라는 개념이 존재한다.
- 이 콜렉션에 해당하는 클래스들은 모두 공통적으로 "동적 할당"이 구현되어 있다.
- 콜렉션에 해당하는 클래스들을 크게 나누면 다음과 같다.
- List : 순서가 존재하고 중복된 객체도 저장 가능하다.
- Set : 순서가 존재하지만 중복된 객체를 저장할 수 없다.
- Map : 순서가 존재하지 않고 중복된 객체를 저장할 수 없다. (단, 저장된 객체를 불러올 때는 미리 약속한 "열쇠(key)" 값으로 불러오게 된다.
2. ArrayList
- 콜렉션에 해당하는 클래스 객체들은 반드시 어떤 클래스 혹은 인터페이스가 모여있는지 적어주어야 한다.
- 적어주는 방법은 각 데이터 타입 옆에 <>를 적고 그 안에 모여있을 클래스를 적어야 한다.
- <>는 Template라고 부른다.
- String 객체들이 모여있을 ArrayList 객체 list
ArrayList<String> list = new ArrayList<>();
- String 객체를 5개 선언 및 초기화해보자.
ArrayList<String> list = new ArrayList<>();
String str1 = "abc";
String str2 = "def";
String str3 = "ghi";
String str4 = "jkl";
String str5 = new String("abc");
- ArrayList 객체의 크기를 확인할 때에는 size()를 사용한다.
System.out.println(list.size());
0
- 현재 ArrayList의 객체가 비어있는지 확인할 때에는 isEmpty()를 사용한다.
System.out.println(list.isEmpty());
true
- ArrayList에 새로운 객체를 추가할 때에는 add(객체)를 사용한다.
list.add(str1);
list.add(str2);
list.add(str3);
list.add(str4);
System.out.println(list.size());
4
- 특정 인덱스에 저장된 객체를 불러올 때에는 get(인덱스)로 불러온다.
System.out.println(list.get(2));
ghi
- ArrayList 객체의 특정 인덱스에 새로운 객체를 끼워 넣으려면 add(인덱스, 객체)를 사용한다.
System.out.println(list.get(1));
list.add(1, "가나다");
System.out.println(list.get(1));
def
가나다
- ArrayList 객체의 특정 인덱스의 객체를 다른 객체로 바꿀 때에는 set(인덱스, 객체)를 사용한다 (단, 해당 메소드는 원래 있던 객체를 리턴한다.)
System.out.println(list.get(0));
String temp = list.set(0, "aaa");
System.out.println(list.get(0));
System.out.println(temp);
abc // set() 전 list.get(0)
aaa // set() 후 list.get(0)
abc // 원래 0번 인덱스에 있던 객체
- ArrayList 객체 안에 저장된 값들을 모두 날릴 때에는 clear()를 사용한다.
System.out.println(list.isEmpty());
list.clear();
System.out.println(list.isEmpty());
false
true
- 비어있는 ArrayList 객체에 다시 String 객체를 추가한다.
list.add(str1);
list.add(str2);
list.add(str3);
list.add(str1);
list.add(str4);
- 이후의 메소드들은 모두 템플릿 클래스 안에 equals() 가 오버라이드 되어있어야 정상적으로 작동하는 메소드들이다.
- 특정 객체가 ArrayList 객체에 존재하는지 찾을 때에는 contains(객체) 를 사용한다.
System.out.println(list.contains(str1));
System.out.println(list.contains("ㅋㅋㅋ"));
System.out.println(list.contains(str5));
true
false
true
- 특정 객체가 ArrayList의 몇 번 인덱스에 있는지 찾을 때에는 indexOf(객체)를 사용한다.
- 가장 먼저 등장하는 인덱스를 불러오며 만약 해당 객체가 존재하지 않으면 -1이 리턴된다.
System.out.println(list.indexOf(str1));
System.out.println(list.indexOf("ㅋㅋㅋ"));
System.out.println(list.indexOf(str5));
0
-1
0
- 특정 객체가 ArrayList의 가장 마지막 등장 인덱스를 찾을 때에는 lastIndexOf(객체)를 사용한다.
- 만약 해당 객체가 존재하지 않으면 -1이 리턴된다.
System.out.println(list.lastIndexOf(str1));
System.out.println(list.lastIndexOf("ㅋㅋㅋ"));
System.out.println(list.lastIndexOf(str5));
3
-1
3
- 특정 인덱스에 저장된 객체를 ArrayList 객체에서 삭제할 때에는 remove(index) 를 사용한다.
System.out.println(list.size());
System.out.println(list.get(1));
list.remove(1);
System.out.println(list.size());
System.out.println(list.get(1));
5 // remove() 전 list.size()
def // remove() 전 list.get(1)
4 // remove() 후 list.size()
ghi // remove() 후 list.get(1)
- 특정 객체와 일치하는 객체를 ArrayList 객체에서 삭제할 때에는 remove(객체) 를 사용한다.
System.out.println(list.contains(str3));
list.remove(str4);
System.out.println(list.contains(str3));
System.out.println(list.indexOf(str1));
list.remove(str5);
System.out.println(list.indexOf(str1));
true // remove(str4) 전 list.contains(str3)
true // remove(str4) 후 list.contains(str3)
0 // remove(str5) 전 list.indexOf(str1)
1 // remove(str5) 후 list.indexOf(str1)
3. 로또
package day0317;
// 6개의 중복되지 않는 랜덤숫자를 뽑아주는 Lotto
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Ex02Lotto {
public static void main(String[] args) {
Random random = new Random();
ArrayList<Integer> list = new ArrayList<>();
while (list.size() < 6) {
Integer temp = random.nextInt(45) + 1;
if (!list.contains(temp)) {
list.add(temp);
}
}
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
Integer num = list.get(i);
}
for (Integer num : list) {
System.out.println(num);
}
}
}
- Collections 라는 클래스의 static 메소드인 sort() 를 사용하면 ArrayList 객체의 정렬을 손쉽게 할 수 있다.
- 만약 콜렉션에 해당하는 클래스 객체를 단순히 출력만 할 때에는 forEach() 라는 특수한 구조를 사용해도 된다.
- 단, 해당 객체의 크기가 변하면 forEach() 구문은 에러가 발생한다.
// forEach 구조
for (템플릿 변수이름 : 콜렉션 객체) {
}
- 위 구조는 다음 코드와 의미가 완전히 동일하다.
for (int i = 0; i < 콜렉션 객체.size(); i++) {
템플릿 변수이름 = 콜렉션 객체.get(i);
}
'~2023.02 > 외부교육' 카테고리의 다른 글
[JAVA] MVC 패턴 (0) | 2022.03.20 |
---|---|
[JAVA] 객체(Object) & 캡슐화(Encapsulation) (0) | 2022.03.19 |
[JAVA] 배열의 동적 할당(Dynamic Allocation) (0) | 2022.03.16 |
[JAVA] Call By Valeue(값에 의한 호출) & Call By Reference(참조에 의한 호출) (0) | 2022.03.15 |
[JAVA] 메서드(Method) (0) | 2022.03.12 |