데이터를 한 곳에 모아놓은 곳
👉 이런 배열 한계 극복 위해 나온 것이 컬렉션
interface
로 만듦interface
끼리 상속가능(아래 구조 사진 참고)
interface
Iterable
interface
Collection
interface
List 👉 ArrayList
interface
Set 👉 HashSet
map은 독립된
interface
interface
Map 👉 HashMap, HashTable
종류 | 기능 |
---|---|
size() : int | 등록된 객체의 개수 |
add(Object obj) : boolean | 특정 객체를 등록 등록에 성공하면 true, 실패하면 false |
get(int index) : Object | index 위치에 있는 객체 |
remove(int index) : Object | index 위치에 있는 객체를 삭제하고, 삭제된 객체를 리턴 |
remove(Object obj) : boolean | 특정 객체를 삭제 삭제에 성공하면 true, 실패하면 false |
contains(Object obj) : boolean | 특정 객체가 존재하는지 확인 객체가 있으면 true, 없으면 false |
isEmplty() : boolean | 객체가 비어있는 지 확인 |
size()
length
와 유사add(93)
Integer.valueof(93)
이 내부에서 자동 변환되어 저장됨remove(int index)
get(int index)
ArrayList
에 데이터가 등록될 때 Object
타입으로 변환되어 저장되므로isEmplty()
<>
모든 종류의 데이터를 저장 가능
⇒ Object 타입으로 데이터를 받아들이기 때문
실제 프로그램에서
타입이 다른 데이터를 컬렉션에 저장하는 경우는 거의 없음
add()
, get()
메서드 활용 // <> 제네릭 => 어떤 객체를 넣을건지 지정
// 끝에 <Book>, <> 이렇게 생략가능
ArrayList<Book> library = new ArrayList<>();
// 요소(엘리먼트)를 딱히 지정안해주면, 기본적으로 10개 잡은 후에, 늘리고 줄이고 자동으로 변경해줌
library.add(new Book("1", "김하나"));
library.add(new Book("2", "이하나"));
library.add(new Book("3", "삼하나"));
library.add(new Book("4", "사하나"));
library.add(new Book("5", "오하나"));
for(int i=0; i<library.size(); i++) {
library.get(i).showInfo();
}
출력 결과
1, 김하나
2, 이하나
3, 삼하나
4, 사하나
5, 오하나
ArrayList
와 완벽하게 동일
< >
을 사용하면 다른 타입의 객체를 저장할 수 없는 것도 똑같음
리스트와의 차이점 및 특징은 하단을 참고해주세요
Student
클래스의 toString()
로 출력ArrayList<Student> studentList = new ArrayList<Student>();
studentList.add(new Student("000005", "오예삐", 66, "운동"));
studentList.add(new Student("000001", "한예삐", 88, "게임"));
studentList.add(new Student("000002", "둘예삐", 100, "당구"));
studentList.add(new Student("000003", "삼예삐", 77, "포커"));
studentList.add(new Student("000004", "사예삐", 44, "테니스"));
studentList.add(new Student("000005", "오예삐", 66, "운동"));
System.out.println("ArrayList 인 경우");
for (Student student : studentList) {
System.out.println(student);
}
System.out.println("");
Set<Student> studentList2 = new HashSet<Student>();
studentList2.add(new Student("000005", "오예삐", 66, "운동"));
studentList2.add(new Student("000001", "한예삐", 88, "게임"));
studentList2.add(new Student("000002", "둘예삐", 100, "당구"));
studentList2.add(new Student("000003", "삼예삐", 77, "포커"));
studentList2.add(new Student("000004", "사예삐", 44, "테니스"));
studentList2.add(new Student("000005", "오예삐", 66, "운동")); // 중복 값
System.out.println("HashSet 인 경우");
for (Student student2 : studentList2) {
System.out.println(student2);
}
출력결과
ArrayList 인 경우
Student [studentNo=000005, name=오예삐, score=66, major=운동]
Student [studentNo=000001, name=한예삐, score=88, major=게임]
Student [studentNo=000002, name=둘예삐, score=100, major=당구]
Student [studentNo=000003, name=삼예삐, score=77, major=포커]
Student [studentNo=000004, name=사예삐, score=44, major=테니스]
Student [studentNo=000005, name=오예삐, score=66, major=운동]
HashSet 인 경우
Student [studentNo=000005, name=오예삐, score=66, major=운동]
Student [studentNo=000004, name=사예삐, score=44, major=테니스]
Student [studentNo=000002, name=둘예삐, score=100, major=당구]
Student [studentNo=000001, name=한예삐, score=88, major=게임]
Student [studentNo=000003, name=삼예삐, score=77, major=포커]
👉 단순히 목록성의 데이터를 저장하고 관리하는 용도로 사용하기에 적합
(Key, Value)
항상 쌍으로 관리됨value
→ 기존에 적용한 객체 타입 외에 다른 타입(new 객체
)은 오류
Key
→ 내가 외우기 편한 문자열로 사용하는 것이 일반적
→ Key
가 중복되면? 덮어써짐!
원래 Key, Value
모두 Object
타입이지만
< >
을 쓰게 되면 해당 타입에 맞춰서 사용
put(“Key값”, value)
value
덮어쓰기(Overwriting)remove(“Key값”)
get("Key값”)
keySet()
Key
목록만 꺼내고 싶을 때 set
(중복허용 X)values()
value
목록만 꺼내고 싶을 때 put()
, keySet()
, values()
메서드 활용하기Map<String, Student> studentList = new HashMap<String, Student>();
// put 방식 1
Student yeppi = new Student("000001", "한예삐", 88, "게임");
studentList.put("000001", yeppi);
// put 방식 2
studentList.put("000003", new Student("000003", "삼예삐", 77, "포커"));
studentList.put("000002", new Student("000002", "둘예삐", 100, "당구"));
System.out.println("번호 목록");
Set<String> key = studentList.keySet();
for (String student : key) {
System.out.println(student.toString());
}
System.out.println("전체 목록");
Collection<Student> information = studentList.values();
for (Student student : information) {
System.out.println(student.toString());
}
출력결과
번호 목록
000003
000002
000001
전체 목록
Student [studentNo=000003, name=삼예삐, score=77, major=포커]
Student [studentNo=000002, name=둘예삐, score=100, major=당구]
Student [studentNo=000001, name=한예삐, score=88, major=게임]
HashMap
과 동일
HashMap보다 HashTable이 조금 더 좋음
자식은 부모 + 자기자신 → 즉, 더 향상된 메소드를 자식 메소드는 가지고 있기 때문
new Hashtable
만 다름put()
, keySet()
, values()
, remove()
메서드 활용하기Map<String, Student> studentList = new Hashtable<String, Student>();
Student yeppi = new Student("000001", "한예삐", 88, "게임");
studentList.put("000001", yeppi);
studentList.put("000003", new Student("000003", "삼예삐", 77, "포커"));
studentList.put("000002", new Student("000002", "둘예삐", 100, "당구"));
System.out.println("번호 목록");
Set<String> key = studentList.keySet();
for (String student : key) {
System.out.println(student.toString());
}
studentList.remove("000002");
System.out.println("전체 목록");
Collection<Student> information = studentList.values();
for (Student student : information) {
System.out.println(student.toString());
}
출력 결과
번호 목록
000003
000002
000001
전체 목록
Student [studentNo=000003, name=삼예삐, score=77, major=포커]
Student [studentNo=000001, name=한예삐, score=88, major=게임]
👉 최상위 부모 타입으로 해주면, 클래스가 바뀌어도 타입 수정할 필요가 없다
👉 번거롭지 않음
👉 ex. Map
을 부모 타입으로 하는 경우, HashTable / HashMap
둘 다 변경하더라도 Map
은 별도의 소스 코드 수정이 없음