algorithm - Best pratice for using array as the key of memoization in Java -


i doing algorithm problems in java, , time time problem needs memoization optimize speed. , times, key array. uses is

hashmap<arraylist<integer>, integer> mem; 

the main reason here use arraylist<integer> instead of int[] hashcode() of primitive array calculated based on reference, arraylist<integer> value of actual array compared, desired behavior.

however, not efficient , code can pretty lengthy well. wondering if there best practice kind of memoization in java? thanks.

update: many have pointed out in comments: bad idea use mutable objects key of hashmap, totally agree.

and going clarify question little bit more: when use type of memoization, not change arraylist<integer> once inserted map. array represents status, , need cache corresponding value status in case visited again.

so please not focus on how bad use mutable object key hashmap. suggest better way kind of memoization please.

update2: @ last choose arrays.tostring() approach since doing algorithm problems on topcoder/codeforces, , dirty , fast code.

however, think hashmap more reasonable , readable way this.

if arraylist contains 3-4 elements,
not worry performance. approach ok.
others pointed out, key mutable is
bad idea.

another approach append elements of arraylist
using separator (say #) , have kind
of string key: 123#555#66678 instead of arraylist of
these 3 integers. can call arrays.tostring(int[])
, decent string key out of array of integers.

i choose second approach.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -