자바맨

  • 홈
  • Github

개발/Java 2

[Java] HashSet.contains() 를 사용하기 위한 @override hashcode()

2차원 배열에 대한 좌표 x, y를 필드로 가지는 객체를 생성후 equals() 를 정의했다. @Override public boolean equals(Object o) { if(o instanceof Pos) { Pos p = (Pos) o; return this.x == p.x && this.y == p.y; } else { return false; } } 하지만, HashSet.contains() 메서드를 사용할 때, 동일한 좌표를 가지는 객체가 존재하더라도 false를 리턴하였다. HashSet은 내부적으로 HashMap을 사용하며, HashMap은 두 객체가 동일한 키임을 판단할 때, 두 hashcode가 같아야 하며, 두 객체가 동일하거나(== 연산결과가 true) 동등해야한다.(equals(..

개발/Java 2022.04.30

[Java] HashMap의 computeIfAbsent(), computeIfPresent(), putIfAbsent() 사용정리

computeIfAbsent() 키가 존재하지 않을때 해당 람다식 실행 해당 키가 존재하던 존재하지 않던 해당 value값을 리턴한다. Map map = new HashMap(); map.computeIfAbsent(1, v -> 1); //키 1이 존재하지 않으므로 1을 삽입 map.computeIfAbsent(1, v -> 2); //키 1이 이미 존재하므로 람다식 실행안됨 System.out.println("size: " + map.size()); map.forEach((k, v) -> System.out.println(k + " " + v)); size: 1 1 1 putIfAbsent() 위의 예시처럼 단순 put 연산을 할 것이라면 putIfAbsent() 메서드를 사용하는게 더 편하다. 이 ..

개발/Java 2021.11.09
이전
1
다음
더보기

Calendar

«   2025/05   »
일 월 화 수 목 금 토
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
  • 분류 전체보기 (39)
    • 개발 (13)
      • Java (2)
      • Kotlin (2)
      • Spring Boot (4)
      • AWS (2)
      • Intellij (1)
      • JUnit (1)
      • Jenkins (0)
      • JSP & Servlet (1)
    • 코딩테스트(Kotlin) (26)
      • LeetCode Top Interview 150 (25)

Tag

leetcode, java, Routing, ModelMapper, EC2, junit, Spring, Tomcat, JSP, ClassNotFoundException, AWS, redis, AMI, cache, spring boot, Servlet, Peering, VPC, spring cache, IntelliJ,

최근글과 인기글

  • 최근글
  • 인기글

Archives

방문자수Total

  • Today :
  • Yesterday :

Copyright © Kakao Corp. All rights reserved.

  • Github

티스토리툴바