본문 바로가기
개념

[이것이 자바다] chapter.15 확인 문제

by cook_code 2023. 4. 4.
반응형

1. 자바의 컬렉션 프레임워크에 대한 설명으로 틀린 것은 무엇입니까?

  1. List 컬렉션은 인덱스로 객체를 관리하며 중복 저장을 허용한다. 
  2. Set 컬렉션은 순서를 유지하지 않으며 중복 저장을 허용하지 않는다. 
  3. Map 컬렉션은 키와 값으로 구성된 Map.Entry를 저장한다. 
  4. Stack은 FIFO(선입선출) 자료구조를 구현한 클래스이다. 

2. List 컬렉션에 대한 설명으로 틀린 것은 무엇입니까?

  1. 대표적인 구현 클래스로는 ArrayList, Vector, LinkedList가 있다. 
  2. 멀티 스레드 환경에서는 ArrayList 보다는 Vector가 스레드에 안전하다. 
  3. ArrayList에서 객체를 삭제하면 삭제한 위치는 비어 있게 된다. 
  4. 중간 위치에 객체를 번번히 삽입하거나 제거할 경우 LinkedList를 사용하는 것이 좋다. 

3. Set 컬렉션에 대한 설명으로 틀린 것은 무엇입니까?

  1. 대표적인 구현 클래스로는 HashSet, LinkedHashSet, TreeSet이 있다. 
  2. Set 컬렉션에서 객체를 하나씩 꺼내오고 싶다면 Iterator를 이용한다. 
  3. HashSet은 hashCode()와 equals()를 이용해서 중복된 객체를 판별한다. 
  4. Set 컬렉션에는 null을 저장할 수 없다. 

4. Map 컬렉션에 대한 설명으로 틀린 것은 무엇입니까?

  1. 대표적인 구현 클래스로는 HashMap, Hashtable, TreeMap, Properties가 있다. 
  2. HashMap과 Hashtable은 hashCode와 equals()를 이용해서 중복된 객체를 판별한다. 
  3. 멀티 스레드 환경에서는 Hashtable보다는 HashMap이 스레드에 안전하다. 
  4. Properties는 키와 값이 모두 String이다. 

5. 단일(싱글) 스레드 환경에서 Bound객체를 저장 순서에 맞게 읽고 싶습니다. 가장 적합한 컬렉션을 생성하도록 밑줄 친 부분에 코드를 작성해보세요.

ArrayList<Board> list = new ArrayList<Board>();

6. 단일(싱글)스레드 환경에서 학번(String)을 키로, 점수(Integer)를 값으로 저장하는 가장 적합한 컬렉션을 생성하도록 밑줄 친 부분에 코드를 작성해보세요.

Map<String, Integer> map = new HashMap<String, Integer>();

7. BoardDao 객체의 getBoundList() 메소드를 호출하면 List<Board> 타입의 컬렉션을 리턴합니다. ListExample 클래스를 실행시켰을 때 다음과 같이 출력될 수 있도록 BoardDao의 getBoardList() 메소드를 작성해보세요.

package org.chapter15;

import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        BoardDao dao = new BoardDao();
        List<Board1> list = dao.getBoardList();
        for(Board1 board:list){
            System.out.println(board.getTitle()+"-"+board.getContent());
        }
    }
}
package org.chapter15;

public class Board1 {
    private String title;
    private String content;

    public Board1(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }
}
package org.chapter15;

import java.util.ArrayList;
import java.util.List;

public class BoardDao {
    //코드 작성

    public List<Board1> getBoardList() {
        List<Board1> list = new ArrayList<Board1>();
        list.add(new Board1("제목1", "내용1"));
        list.add(new Board1("제목2", "내용2"));
        list.add(new Board1("제목3", "내용3"));
        return list;
    }


}

8. HashSet에 Student 객체를 저장하려고 합니다. 학번이 같으면 동일한 Student라고 가정하고 중복 저장이 되지 않도록 하고 싶습니다. Student  클래스에서 재정의 해야 하는 hashCode()와 equals() 메소드의 내용을 채워보세요. Student의 해시코드는 학번이라고 가정합니다. 

package org.chapter15;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetExample {
    public static void main(String[] args) {
        Set<Student> set = new HashSet<Student>();

        set.add(new Student(1, "홍길동"));
        set.add(new Student(2, "신용권"));
        set.add(new Student(1, "조민우"));

        //반복자 얻기
        Iterator<Student> iterator = set.iterator();
        //객체 수만큼 루핑
        while (iterator.hasNext()) {
            //한 개의 객체를 가져온다.
            Student student = iterator.next();
            System.out.println(student.studentNum + ":" + student.name);
        }
    }
}
package org.chapter15;

import java.util.Objects;

public class Student {
    //필드값
    public int studentNum;
    public String name;

    //생성자
    public Student(int studentNum, String name) {
        this.studentNum = studentNum;
        this.name = name;
    }

    //eqauls, hashcode 메소드 오버라이딩
    @Override
    public boolean equals(Object o) {
        if (o instanceof Student) {
            Student student = (Student) o;
            return (studentNum == student.studentNum) && (name.equals(student.name));
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return studentNum + name.hashCode();
    }
}

9. HashMap에 아이디(String)와 점수(Integer)가 저장되어 있습니다. 실행 결과와 같이 평균 점수를 출력하고, 최고 점수와 최고 점수를 받은 아이디를 출력해보세요.

package org.chapter15;

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("blue", 96);
        map.put("hong", 86);
        map.put("white", 92);

        //최고 점수를 받은 아이디 저장
        String name = null;
        //최고 점수 저장
        int maxScore = 0;
        //점수 합계 저장
        int totalScore = 0;

        //평균 점수
        double avg = 0;

        //작성위치, map을 이용해 구현
        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        Iterator<Map.Entry<String, Integer>> entryIterator = entrySet.iterator();

        while (entryIterator.hasNext()) {
            Map.Entry<String, Integer> entry = entryIterator.next();
            totalScore += entry.getValue();
            for (Map.Entry<String, Integer> entry1 : entrySet) {
                if (entry1.getValue() > maxScore) {
                    name = entry1.getKey();
                    maxScore = entry1.getValue();
                }
            }
        }
        avg = totalScore / map.size();


        System.out.println("평균점수: " + avg);
        System.out.println("최고점수: " + maxScore);
        System.out.println("최고점수를 받은 아이디: " + name);

    }
}

10. TreeSet에 Student 객체를 저장하려고 합니다. Student의 score 필드값으로 자동 정렬하도록 구현하고 싶습니다. TreeSet의 last() 메소드를 호출했을 때 가장 높은 score의 Student 객체가 리턴되도록 Student 클래스를 완성해보세요.

package org.chapter15;

import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        TreeSet<Student1> treeSet = new TreeSet<>();
        treeSet.add(new Student1("blue", 96));
        treeSet.add(new Student1("hong", 86));
        treeSet.add(new Student1("white", 92));

        Student1 student1 = treeSet.last();
        System.out.println("최고점수: "+student1.score);
        System.out.println("최고점수를 받은 아이디: "+student1.id);

    }
}
package org.chapter15;

import com.sun.source.tree.Tree;

public class Student1 implements Comparable<Student1> {
    public String id;
    public int score;

    public Student1(String id, int score) {
        this.id = id;
        this.score = score;
    }

    public String getId() {
        return id;
    }

    public int getScore() {
        return score;
    }

    @Override
    public int compareTo(Student1 o) {
        //코드 작성
        if(score<o.score) {
            return -1;
        } else if (score==o.score) {
            return 0;
        }else {
            return 1;
        }

    }
}

 

반응형