O_O
O_O

Reputation: 4477

How to dynamically store information into a data structure containing string and integers in Java

I am reading from a spreadsheet with contents such as the following:

             Yr1     Yr2     Yr3
Utilities    345     482     519

I would like to store the Utilities string, and 345, 482, and 519 as integers in some sort of array corresponding to the string. I believe I can store this information as a HashSet<object> but I am confused how to make this flexible so that it can be dynamically allocated for future years. Is there an easy way to output this information into a data structure if the number of total years (number of columns with data) is unknown? Or would I always need to check the number of years and set that within my object?

Thanks.

Upvotes: 0

Views: 91

Answers (1)

LionH
LionH

Reputation: 324

In this case, I would create a class containing the data structures and exposing method access to the data. This ensure to encapsulate the logical access to the data if performance enhancement are made. For example:

public class DataStructure {
    private String rowTitle;
    private Map<String, Integer> dynamicColumns;

    public DataStructure() {
        dynamicColumns = new HashMap<String, Integer>();
    }

    public String getRowTitle() {
        return rowTitle;
    }
    public void setRowTitle(String rowTitle) {
        this.rowTitle = rowTitle;
    }

    public void addDynamicColumn(String title, Integer value) {
        dynamicColumns.put(title, value);
    }

    public Integer getDynamicColumn(String title) {
        return dynamicColumns.get(title);
    }
}

you will able to add whatever method access lately depending on the business needs.

Upvotes: 1

Related Questions