2015-02-03 4 views
0

현재이 코드가 있습니다.3 HashMaps 인쇄 - Java

import java.util.HashMap; 

public class Products { 
    HashMap<Integer, String> id = new HashMap<>(); 
    HashMap<Integer, String> dtion = new HashMap<>(); 
    HashMap<Integer, Double> amount = new HashMap<>(); 

다음 예제 데이터를 생성자를 통해 각 HashMap에 추가했습니다. 설명과 가격과 함께 ProductID를 출력하기 위해이 세 가지 HashMap을 가지고 있습니다. 즉, ProductID는 3 개의 HashMaps에서 같은 항목에 대해 동일합니다. 이러한 항목을 한 줄로 어떻게 인쇄합니까? 예 : 품목 1, 품목 3.20입니다. Item2, 이것은 또 다른 항목으로 5.10 대신 첫 번째 HashMap에서 모든 항목을 출력하고 두 번째 HashMap 다음에 세 번째 항목을 표시합니다.

+0

왜 한 줄만 쓰고 싶습니까? – Maroun

+0

단일 '맵'을 사용하지 않는 이유는 무엇입니까? –

+0

이 맵을 상위 맵에 추가하십시오. 부모지도를 반복합니다. StringBuffer에 값을 넣고, 마지막으로 인쇄하십시오. – Jango

답변

2

그것은 만들 수있는 더 의미를 만들 수있는 Product 클래스 productID, descriptionprice을 가지고, 오직이 방법보다는 대신 3

public class Product 
{ 
    private String productID; 
    private String description; 
    private double price; 

    public Product (String productID, String description, double price) 
    { 
     this.productID = productID; 
     this.description = description; 
     this.price = price; 
    } 

    public String toString() 
    { 
     return productID + ", " + description + ", " + price; 
    } 
} 

public class Products 
{ 
    public static void main (String[] args) 
    { 
     HashMap<Integer, Product> products = new HashMap<>(); 
     products.put (1, new Product("Item1","This is an item", 3.20)); 
     products.put (2, new Product("Item2","This is another item", 5.10)); 
     ... 
    } 
} 
+0

어떻게 그 일을 할 것입니까? – james11

+0

@ james11 수정 된 답변 – Eran

+0

하지만 이렇게하면 - 제품 ID, 설명 및 가격은 하나의 가치를 가질 수 있습니다. 10 개 이상의 항목을 추가하고 싶습니다. 제품 ID에 10 개의 값을, 설명에 10을, 가격에 10을 원합니다. – james11

1

사용하십시오 Map<Integer, Product>의 단일 HashMap를 사용합니다. Product에는 원하는/필요한 모든 필드를 저장할 수 있습니다. 당신이 HashMaps을 함께 할 경우

public class Products { 
    Map<Integer, Product> productMap = new HashMap<>(); 
    //rest of the class... 
} 
1

:

public String getProductString(final int pKey){ 
return "ID: "+productId.get(pKey)+" Description: "+description.get(pKey)+" Price: "+String.valueOf(price.get(pKey)); 
} 

당신은 당신의 자신의 클래스를 만들 경우 예 :

public class Product { 
    private String productId; 
    private String description; 
    private double price; 

    //getters and setters... 

    //toString method 
} 

그런 다음 Products 클래스의 단일지도를하기 만하면됩니다 :

public class Product{ 

private double price; 
private String productId; 
private String description; 

public Product(final double pPrice, final String pProductId, final String pDescription){ 
    this.price = pPrice; 
    this.productId = pProductId; 
    this.description = pDescription; 
} 

@Override 
public String toString(){ 
    return "ID: "+productId+" Description: "+description+" Price: "+price 
} 

} 

클래스 제품의 인스턴스가 있으면 그것에 대해 toString()을 호출하면 값을 반환합니다.