问题
What is the difference between:
- Object put(Serializable key, Object value)
- void add(Serializable key, Object value)
methods in StateHelper in JSF?
回答1:
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.
回答2:
From the Mojarra API documentation:
void add(java.io.Serializable key, java.lang.Object value)
Store the specified value in a List that is internal to the StateHelper.java.lang.Object put(java.io.Serializable key, java.lang.Object value) Return the previously stored value and store the specified key/value pair.
I guess MyFaces implemented it in a similar way.
来源:https://stackoverflow.com/questions/12180097/what-is-the-difference-between-put-and-add-method-in-statehelper-in-jsf-2