Frage

I'm new to Java (and not too comfortable with strong typing) and I have a method that takes in a HashMap. A key in this hashmap contains a key, which has a hashmap for value, which also points to a hashmap, etc, until we reach a string:y

HashMap1->HashMap2->HashMap3->HashMap4->String

I am trying to access it as follows:

HashMap1
    .get("aKey")
    .get("anotherKey")
    .get("yetAnotherKey")
    .get("MyString");

But then I get an error,

Object does not have a method "get(String)

Here is the method, simplified:

public HashMap<String, HashMap> getMyString(Map<String, HashMap> hashMap1) {
    String myString = hashMap1
                          .get("aKey")
                          .get("anotherKey")
                          .get("yetAnotherKey")
                          .get("MyString");

    // do something with myString.

    return hashMap1;
}

How would someone properly define the method and the parameters to access nested elements easily?

Thank you,

War es hilfreich?

Lösung

Simple as that

HashMap1.get("aKey") -- > return hashMap2
.get("anotherKey") --> return hashMap3
.get("yetAnotherKey") --> return hashMap4
.get("MyString"); --> return String

There is something wrong with the adding part.

Now you have structure like below.

hashmap1 --> hashmap2 --> String 

String myString = hashMap1.get("aKey").get("MyString");

That is how it should be.

Andere Tipps

You made too many .get calls. Probably the last one is not needed.

Can you just create class CompoundKey with arbitrary number of String fields and use it as a key? It would simplify your design.

To use it properly in Java you need to override hashCode and equals methods.

You should first of all use interfaces not implementation, therefore use Map (and not HashMap) where possible.

And second, you should repair your Generics and use all levels. Now the compiler can help you and possible show your error.

// i suppose you want to return a String, at least the method name tells it
public String getMyString(Map<String, Map<String, Map<String, Map<String, String>>>> hashMap1) {
    String myString = hashMap1
                      .get("aKey")
                      .get("anotherKey")
                      .get("yetAnotherKey")
                      .get("MyString");

    return myString;
}

Yet i suggest that you use a different data structure.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top