반응형
콜렉션(Collection)
- 여러 원소를 담을 수 있는 자료구조
- List, Set, Queue로 크게 3가지 인터페이스로 분류.
- Map은 collection 인터페이스를 상속받고 있지 않지만 collection으로 분류 한다.
[배열과의 차이점] 배열은 정적으로 메모리 할당. 콜랙션은 동적으로 메모리 할당.
콜렉션의 종류
Map
- (Key, Value) 형태로 저장한다.
HashMap
- 동기화 보장X
- 순서 보장X
package D09;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Scanner;
class Student{
public int sno;
public String name;
public Student(int sno, String name) {
this.sno = sno;
this.name = name;
}
@Override
public String toString() {
return String.format("학번 -%s 이름 -%s", sno, name);
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student) {
Student s = (Student) obj;
return (sno == s.sno) && (name.equals(s.name));
}else {
return false;
}
}
@Override
public int hashCode() {
return sno+name.hashCode();
}
}
public class HasgMapStd {
public static void main(String[] args) {
Map<Student, Integer> map = new HashMap<>();
map.put(new Student(1, "홍길동"), 95);
map.put(new Student(2, "김덕배"), 100);
map.put(new Student(3, "춘향이"), 75);
int maxScore = 0;
int totalScore = 0;
int avgScore = 0;
Student maxStd = null;
Set<Map.Entry<Student, Integer>> entrySet = map.entrySet();
for(Map.Entry<Student, Integer> entry : entrySet) {
if(entry.getValue()>maxScore) {
maxStd = entry.getKey();
maxScore = entry.getValue();
}
totalScore += entry.getValue();
}
avgScore = totalScore / map.size();
System.out.println("최고 점수인 학생 : "+maxStd);
System.out.println("점수 : "+maxScore);
System.out.println("전체 평균 : "+avgScore);
}
}
HashTable
- HashMap과 거의 동일하지만, 동기화 보장O
package D09;
import java.util.*;
public class HashTableEx {
public static void main(String[] args) {
Map<String, String> map = new Hashtable<String, String>();
map.put("spring", "12");
map.put("summer", "123");
map.put("fall", "1234");
map.put("winter", "12345");
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("아이디와 비밀번호를 입력하세요.");
System.out.print("아이디 : ");
String id = sc.nextLine();
System.out.println("아이디와 비밀번호를 입력하세요.");
System.out.print("비밀번호 : ");
String pw = sc.nextLine();
if(map.containsKey(id)) {
if(map.get(id).equals(pw)) {
System.out.println(id + "님 반갑습니다.");
break;
}else {
System.out.println("비밀번호가 틀렸습니다.");
}
}else {
System.out.println("회원정보가 없습니다.");
}
}
}
}
TreeMap
- 정렬된 순서대로 키, 값 저장
- 검색 빠름
LinkedHashMap
- 연결리스트로 구현한 HashMap
- 순서 보장O
반응형
'JAVA' 카테고리의 다른 글
[JAVA] Beep (0) | 2023.07.19 |
---|---|
[JAVA] Thread (0) | 2023.07.19 |
[JAVA] Collection(Stack) (0) | 2023.07.18 |
[JAVA] Collection(Queue) (0) | 2023.07.18 |
[JAVA] Collection(Set) (0) | 2023.07.18 |