Jordan
Jordan

Reputation: 31

Creating unique ArrayList for each Hash Map key value - Java

I am trying to read in information about the inputs to each gate in a circuit simulator I'm making. The file information for the input connections looks like this:

// Connections from inputs to gates (inputLabel, gateLabel)
INPUT(A, AND1)
INPUT(B, AND1)
INPUT(B, AND2)
INPUT(C, AND2)

I am trying to create a Map with the key being the gateLabel, and storing the inputLabel information.

I.e. -


Key --- Info
AND1 | A,B
AND2 | B,C

The code I have at the moment is this:

String inputCircuitLabel = params[0];
String inGateLabel = params[1];

    if(!iConnM.containsKey(inGateLabel)){

          inputCircuitLabels.add(inputCircuitLabel);
          iConnM.put(inGateLabel, inputCircuitLabels);              

    }

    else{

          inputCircuitLabels.add(inCircuitLabel);

    }

I was wondering if there is an intuitive way to make a separate class, and make a call to it something like:

GateInput gi = new GateInput(inGateLabel);
ArrayList<GateInput> al;

In order to get a unique arrayList for each gateLabel. Because at the moment AND2 ends up referencing A,B,B,C instead of just B,C.

Upvotes: 0

Views: 493

Answers (1)

Andy Guibert
Andy Guibert

Reputation: 42956

You should be able to accomplish this with a Map of String->List. Using this approach, each gate label will get it's own unique List of circuit labels.

Example code:

Map<String, List<String>> iConnM = new HashMap<String, List<String>>();

String inputCircuitLabel = params[0];
String inGateLabel = params[1];

if (!iConnM.containsKey(inGateLabel)) {
    iConnM.put(inGateLabel, Arrays.asList(inputCircuitLabel));
} else {
    iConnM.get(inGateLabel).add(inputCircuitLabel);
}

Upvotes: 1

Related Questions