2

I know that such "general" questions shouldn't be asked, but can someone help me translate the following code from Groovy to Java. My main problem is, that I really do not know which datatypes in Java are similar to the ones of Groovy. Any help is welcome!

Many thanks!

  def registrations = [:]

  public void register(Class clazz, MessageListener listener) {
      def listeners = registrations.get(clazz)
      if (!listeners) {
          listeners = [] as Set;
          registrations.put(clazz, listeners)
       }
       listeners << listener
   }

3 Answers 3

3

It would be something like this (untested):

Map<Class, Set<MessageListener>> registrations = new HashMap<Class, Set<MessageListener>>();

public void register(Class clazz, MessageListener listener) {
    Set<MessageListener> listeners = registrations.get(clazz);
    if (listeners == null) {
        listeners = new HashSet<MessageListener>();
        registrations.put(clazz, listeners);
     }
     listeners.add(listener);
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I posted mine 4 seconds before you, so I win! ;D Edit: Or maybe not, since mine does not compile because of lacking semi-colons. Edit2: But I fixed that, too.
shamefully deletes his post
2

Not an answer to the question (@Stmated has that covered), but if this is for a comparison to compare Groovy and Java, I believe your Groovy code could be better:

def registrations = [:].withDefault { [] as Set }

public void register(Class clazz, MessageListener listener) {
  registrations[ clazz ] << listener
}

1 Comment

Can you help me with my question
1

Simply use java.util.HashMap and java.util.HashSet for registrations and listeners respectively.

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.