Search code examples
jsf-2java-ee-6myfacescomposite-componentuicomponents

What is the difference between put and add method in statehelper in JSF 2


What is the difference between:

  • Object put(Serializable key, Object value)
  • void add(Serializable key, Object value)

methods in StateHelper in JSF?


Solution

  • I found the api documentation not that helpful myself and investigated it. Each time add is called it appends another value to a list which is saved under the given key. If you call a get on that key you get back a list. The add method saves you creating that list and watches for corner cases, ex. creating the list when the key is empty.

    The put you mentioned works similar to a map-like put. It saves a value under a key.

    In contrast, there is an overloaded put with 3 parameters. It creates a map under that key and does a put on that map with another pair of key/value. Again, a get on the key gives you a map.

    Thats basically how add and put work. There is some more going on to make partial states working. To sum it up: when you want to add several values under a key you can use add. put with 2 parameters gives you map-like behavior. put with 3 parameters allows you to fill a map under a key.