0

so that's my situation:

I have a method which gets a String and a bunch of other information. Depending on the content of the String, I want to put the other information into one of two Maps I have. Like this:

if (string.equals("A")) {
  A.put[..]
} else if (string.equals("B")) {
  B.put[..]
}

but because this situation happens a few times in my method, I don't want to use if/else every time because of redundancy.

Soo I guess what I need is some kind of object/pointer/reference which I can assign the Map I want to use once in the beginning and then use it as a placeholder.

3
  • So ... you want a conditional statement, without an actual conditional statement? .... Commented Jan 22, 2016 at 14:29
  • 1
    if it happens only a few times, you'd better leave the things as is. Commented Jan 22, 2016 at 14:35
  • @Stultuske I want less conditional statements, not noone. Which I realized using ctsts answer. Commented Jan 22, 2016 at 15:00

2 Answers 2

1

That's why we have reference variables:

Map<?,?> map;
if(string.equals("A"))
    map = A;
else if(string.equals("B"))
    map = B;
else
    map = new HashMap<>();

works fine. The last line is more like an error-check for your String and will be garbage collected after your method is finished (otherwise map might not be initialised, which would throw a NullPointer). After this you can put everything into map (thank reference variables :-) ). Remember map is just a reference to your Map A or B (or "void")

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I've been writing stuff in Java for 3 years and didn't know that. Shame on me. Thanks!
1

It appears you want a Map of Maps.

Map<String, Map<?, ?>> maps = new HashMap<>();

Map<?, ?> map = map.get(string);
map.put[...];

if you want to add the map as required you can use

Map<?, ?> map = map.computeIfAbsent(string, HashMap::new);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.