public synchronized Object put ( Object obj ) { // This implementation is based on the IdentityMap.put method. if ( obj == null ) { return null ; } Entry tab [ ] = mTable ; int hash = hashCode ( obj ) ; int index = ( hash & 0x7FFFFFFF ) % tab . length ; for ( Entry e = tab [ index ] , prev = null ; e != null ; e = e . mNext ) { Object iobj = e . get ( ) ; if ( iobj == null ) { // Clean up after a cleared Reference. if ( prev != null ) { prev . mNext = e . mNext ; } else { tab [ index ] = e . mNext ; } mCount -- ; } else if ( e . mHash == hash && obj . getClass ( ) == iobj . getClass ( ) && equals ( obj , iobj ) ) { // Found flyweight instance. return iobj ; } else { prev = e ; } } if ( mCount >= mThreshold ) { // Cleanup the table if the threshold is exceeded. cleanup ( ) ; } if ( mCount >= mThreshold ) { // Rehash the table if the threshold is still exceeded. rehash ( ) ; tab = mTable ; index = ( hash & 0x7FFFFFFF ) % tab . length ; } // Create a new entry. tab [ index ] = new Entry ( obj , hash , tab [ index ] ) ; mCount ++ ; return obj ; }
Pass in a candidate flyweight object and get a unique instance from this set . The returned object will always be of the same type as that passed in . If the object passed in does not equal any object currently in the set it will be added to the set becoming a flyweight .