Home > Mobile >  Data Structure that holds two objects at each index (Java)
Data Structure that holds two objects at each index (Java)

Time:10-24

I have a Product class, and a DerivedProduct class that extends Product. Derived Products are a combination of 2 or more different Products (and can be various quantities of each product). For example, the Derived Product Water is made of 2 Hydrogen Products and 1 Oxygen Product.

I want an attribute for DerivedProduct that is a structure that contains both which products its made of and the quantity of each one. What data structure can I use? ArrayList for example only lets me (to my knowledge) hold one Object per index, but I want two (Product object and an integer)

CodePudding user response:

Any kind of Map (for example HashMap) will do what you want. Use the Product as the key and an Integer representing the count as the value. So you might write

public class DerivedProduct extends Product {
    private Map<Product, Integer> contents = new HashMap<>();

    public void putProduct(Product product, Integer count) {
        contents.put(product, count);
    }

    public int getCount(Product product) {
        Integer count = contents.get(product);
        return count == null ? 0 : count;
    }
}

Make sure you have suitable equals and hashCode method defined in the Product class to make this work properly.

CodePudding user response:

A Map<Product, Integer> is one possibility; see @Dawood's answer.

But if you don't need the lookup operations provided by a Map, then you could use one of these alternatives:

  • List<CustomClass> where CustomClass has a Product field and an int field to hold the count. (The custom class could potentially be a record class in Java 17.)

  • List<Object[]> where the Object[] arrays contain a Product and an Integer.

  • Analogs of the above using an array instead of a list.

From an OO design and type-safety perspective the Map and List<CustomClass> versions are "on a par". It comes down to a trade-off between the functionality versus runtime overheads1.


1 - Specifically, the memory overheads of the data structures and the CPU overheads of the operations that you are going to use. But note that these overheads may well be irrelevant ... depending on your application.

  • Related