본문 바로가기

백엔드/JAVA

java - map

 

package collection_framework;

import java.awt.image.ImageProducer;
import java.util.HashMap;
import java.util.Map;

public class MapDemo {

  public static void main(String[] args) {
    Map<String, Integer> map = Map.of("딸기",5,"바나나",3,"사과",2);
    //"딸기"와 숫자 파라미터를 넣어준다.
    HashMap<String, Integer> hm = new HashMap<>(map);
    System.out.println(hm.size());

    System.out.println(hm.get("딸기"));
    hm.put("딸기",10);
    System.out.println("바나나갯수"+hm.get("바나나"));

    hm.put("수박",222);
    System.out.println(hm.size());
    System.out.println("수박갯수"+hm.get("수박"));
  } }

 

 

map2 실습

public class MapDemo2 {

  public static void main(String[] args) {
    Map<Fruit, Integer> fruits = new HashMap<>();
    Fruit f1 = new Fruit("사과");
    Fruit f2 = new Fruit("딸기");
    fruits.put(f1,5);
    fruits.put(f2,3);
    fruits.put(f1,10);

    System.out.println(fruits.size());
    System.out.println(fruits.get(f2));
  }}

class Fruit{
  String name;

  @Override
  public String toString() {
    return name;
  }

  public Fruit(String name) {
    this.name = name;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Fruit fruit)) return false;
    return Objects.equals(name, fruit.name);
  }
  @Override
  public int hashCode() {
    return Objects.hashCode(name);
    
  }}

 

반응형

'백엔드 > JAVA' 카테고리의 다른 글

절차지향 vs 객체지향(인프런실습)  (0) 2024.08.29
ch06. 타입변환과 다형 8/22  (0) 2024.08.28
java - lambda  (0) 2024.08.28
JAVAerror로그  (0) 2024.08.26
오버라이딩  (0) 2024.08.21