본문 바로가기
Study/JSP

[JSP] HashMap

by YoungD 2023. 9. 24.

 

 HashMap 

해시맵은 이름 그대로 해싱(Hashing)된 맵(Map)

Map 인터페이스를 구현한 Map 컬렉션 중 하나이다

Map 인터페이스를 상속하고 있기 때문에 Map의 성질을 그대로 가지고 있음

 

사용하는 이유 : 많은 양의 데이터를 검색하는 데에 뛰어난 성능을 보임

단점 : 저장이 느리다

 

 


# Map

 

키(Key)와 값(Value)으로 구성된 Entry 객체를 저장하는 구조를 가지고 있는 자료구조(여기서 키와 값은 모두 객체)

자바에서 HashMap은 Map의 일종이며, key : value 형태로 데이터를 저장하기위해 사용

 


 

 

 

class생성

 

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

   map.put("이름", "youngD");

 

   String name = map.get("이름");

 

   System.out.println(name);

HashMap 선언 & 생성

  • Key, Value 2개의 값을 가지고 있으므로 타입을 선언하려면 두 개의 타입을 선언해야한다
  • Key와 Value를 파라미터로 주는 Put 메소드를 사용한다
  • HashMap에 값을 추가하려면 put(Key, Value) 메서드를 사용하면 된다
  • 키는 고유한 속성이며 중복 허용x, 값은 고유한 속성이 아니며 중복을 허용
  • 만약 같은 키 값의 데이터를 put하면 기존의 Value가 나중에 넣은 Value로 변경이 된다

 

 

 

<FrontController>

   HashMap 생성

   HashMap<String, ICommand> map = new HashMap<>();

 

   @Override

   public void init() throws ServletException {

   // TODO Auto-generated method stub

   super.init();

    누군가에 의해서 현재 서블릿에 들어오게 된다면 서블릿을 실행할 수 있게 서블릿 객체를 생성하는 메소드

    이 메소드는 최초에 의해 한 번만 실행됨(싱글톤패턴)

 

   map.put("JoinService.do", new JoinService());

   map.put("LoginService.do", new LoginService());

   map.put("LogoutService.do", new LogoutService());

   map.put("UpdateService.do", new UpdateService());

   map.put("MsgSendService.do", new MsgSendService());

   map.put("MsgAllDelete.do", new MsgAllDelete());

   map.put("MsgDelete.do", new MsgDelete());

   }

   map.put(getServletInfo(), key값 / icommand타입으로 형변환 - 업캐스팅);

   private static final long serialVersionUID = 1L;

싱글톤패턴 : 생성자가 여러 차례 호출되더라도 실제로 생성되는 객체는 하나이고 최초 생성 이후에 호출된 생성자는 최초의 생성자가 생성한 객체를 리턴

 

 

 

 

 

<FrontController>

   ICommand service = map.get(command);

   String moveUrl = service.execute(request, response);

   response.sendRedirect(moveUrl);

   response.sendRedirect(map.get(command).execute(request, response));

   command 에 요청 url이 담기고 (거기에 해당되는) map에서 요청하는 객체가

   map.get map 에서 꺼내면 해당되는 서비스 객체가 나오며 execute 실행 -> url을 돌려줌(response.sendRedirect)

 

특정 key값의 value를 가져오고싶다면 get(key)를 사용하면 된다

(전체를 출력하려면 entrySet()이나 keySet()메소드를 활용하여 Map의 객체를 반환받은 후 출력하면 됨)

 

 

 

 

<FrontController>

   protected void service(HttpServletRequest request, HttpServletResponse response)

   throws ServletException, IOException {

 

   1. client가 요청한 URL주소 가져오기

   String requestURI = request.getRequestURI();

 

   2. Context Path (웹 어플리케이션의 시작 주소)

   String contextPath = request.getContextPath();

 

   3. client 요청 부분만 분리

   String command = requestURI.substring(contextPath.length() + 1);

 

   request.setCharacterEncoding("EUC-KR");

//   ICommand service = map.get(command);

//   String moveUrl = service.execute(request, response);

//   response.sendRedirect(moveUrl);

   response.sendRedirect(map.get(command).execute(request, response));

   }

코드 간결화