📃 인스턴스 생성하기
Product p1 = new Product("p1003", "컴퓨터", 1023900);
Product p2 = new Product("p1005", "세탁기", 789800);
Product p3 = new Product("p1008", "에어컨", 479800);
📃 ArrayList에 저장하기
ArrayList<Product> ap = new ArrayList<>();
ap.add(p1);
ap.add(p2);
ap.add(p3);
📃 toString() 오버라이딩
@Override
public String toString() {
return "상품코드 : " + productCode + ", 상품명 : " + productName + ", 가격 : " + price ;
}
📌 기본출력하기
for(int i =0; i<ap.size(); i++) {
System.out.printf("상품명 : %s, 가격 : %d\n", ap.get(i).getProductName(), ap.get(i).getPrice());
}
📌 향상된 for문으로 출력하기 + HashMap에 넣기(put메소드)
HashMap<String, Product> mapAp = new HashMap<String, Product>();
for(Product p : ap) {
System.out.printf("상품코드 : %s, 가격 : %d\n", p.getProductCode(), p.getPrice());
mapAp.put(p.getProductCode(), p);
}
📌 entrySet 메소드로 HashMap 출력
entrySet()
: key와 value를 set으로 가져옴
for(Entry<String, Product> entry : mapAp.entrySet()) {
System.out.printf("key : %s - %s\n", entry.getKey(), entry.getValue());
}
📌 keySet 메소드로 HashMap 출력
keySet()
: key를 set으로 가져옴
Set<String> keySet = mapAp.keySet();
for(String key : keySet) {
System.out.printf("key : %s - %s\n", key, mapAp.get(key));
}
📌 iterator 메소드로 HashMap 출력
HashMap
은 Collections
를 상속하지 않기 때문에 Iterator를 바로 쓸수 없음
참고 : HashSet
은 Collections
상속
Set<String> keySet = mapAp.keySet();
Iterator<String> iter = keySet.iterator();
while(iter.hasNext()) {
String key = iter.next();
System.out.printf("key : %s - %s\n", key, mapAp.get(key));
}