2013년 1월 17일 목요일

[Java] HashMap 예제


void addGroup(String group){
if(!map.containsKey(group)){
map.put(group, new ArrayList<PhoneInfo>());
}
}

void Input(){
System.out.print("그룹 입력 : ");
String group = sc.nextLine();
System.out.print("이름 입력 : ");
String name = sc.nextLine();
System.out.print("전화 번호 입력 : ");
String phone = sc.nextLine();
System.out.print("생일 입력 : ");
String birth = sc.nextLine();

addGroup(group);
ArrayList<PhoneInfo> list = map.get(group);
   list.add(new PhoneInfo(name, phone, birth));
   System.out.println();
}

void show(){
Set set = map.entrySet();
Iterator iter = set.iterator();

while(iter.hasNext()){
Map.Entry e = (Map.Entry)iter.next();
Iterator iterSub = ((ArrayList)e.getValue()).iterator();

System.out.println(e.getKey());

while(iterSub.hasNext()){
PhoneInfo pi = (PhoneInfo)(iterSub.next());
pi.showInfo();
}
System.out.println();
}
System.out.println();
}

void modify(){
System.out.print("전화번호부 수정할 사람의 이름을 입력해 주십시오");
String name = sc.nextLine();

Set set = map.entrySet();
Iterator iter = set.iterator();

while(iter.hasNext()){
Map.Entry e = (Map.Entry)iter.next();
Iterator iterSub = ((ArrayList)e.getValue()).iterator();

while(iterSub.hasNext()){
PhoneInfo pi = (PhoneInfo)(iterSub.next());
if(pi.name.equals(name)){
System.out.print("수정할 전화번호를 입력하세요");
String phone = sc.nextLine();
pi.phoneNum = phone;
}
}
}
System.out.println();
}

void delete(){
System.out.print("삭제할 사람의 이름을 입력해 주십시오.");
String name = sc.nextLine();

Set set = map.entrySet();
Iterator iter = set.iterator();

while(iter.hasNext()){
Map.Entry e = (Map.Entry)iter.next();
Iterator iterSub = ((ArrayList)e.getValue()).iterator();

while(iterSub.hasNext()){
PhoneInfo pi = (PhoneInfo)(iterSub.next());
if(pi.name.equals(name)){
iterSub.remove();
}
}
}
}

void sort(){
Comparator<PhoneInfo> cp = new Comparator<PhoneInfo>() {

@Override
public int compare(PhoneInfo o1, PhoneInfo o2) {
// TODO Auto-generated method stub
if(o1.name.compareTo(o2.name)<0)
return -1;
else if(o1.name.compareTo(o2.name)>0)
return 1;
return 0;
}
};

Set set = map.entrySet();
Iterator iter = set.iterator();
System.out.print("정렬할 그룹를 입력하세요");
String group = sc.nextLine();

while(iter.hasNext()){
Map.Entry e = (Map.Entry)iter.next();

if(e.getKey().equals(group))
Collections.sort(((ArrayList)e.getValue()), cp);

}
System.out.println();
}

---------------------------------------------------------------------------------

HashMap 안에 HashMap 또는 ArrayList를 사용할 수 있다. 옆에 간략하게 나타낸 이미지를 통해 어떤 메소드를 호출하고 형변환이 일어나는지 잘 파악해보자.

댓글 없음:

댓글 쓰기