Constant arrays in Java -
i have move
class, immutable (basically it's 2 ints).
the have class moves
constants:
public class moves { public static final move nw = move.make(-1, -1); public static final move n = move.make(0, -1); public static final move ne = move.make(1, -1); public static final move e = move.make(1, 0); public static final move se = move.make(1, 1); public static final move s = move.make(0, 1); public static final move sw = move.make(-1, 1); public static final move w = move.make(-1, 0); public final static move[] = { nw, n, ne, e, se, s, sw, w }; public final static move[] cardinal = { n, e, s, w }; }
i need arrays methods such as:
public void walktorandomside(move[] possiblemoves)
it works nicely, - - elements of all
, cardinal
can changed anytime anyone. know elements cannot made final, of course.
that bad - want part of library , stable , predictable possible.
how work around this? make method creates new array each time?
no, avoid using arrays. arrays always mutable, , if create new array each time, means callers have perform defensive copies if pass sets around.
firstly, i'd change move
class enum steve suggested. can use enumset.allof
.
secondly, cardinal
either use collections.unmodifiablelist
wrap list you'd created internally (and know you're never going modify yourself), or use type explicitly talks immutability, such immutablelist
guava (or perhaps immutableset
, depending on whether ordering important or not).
the benefit of using separate type can make clear callers is immutable, rather documenting list that's been returned happens immutable. while it's idea use interface return type, here it's worth communicating concrete guarantee in type system - guarantee callers can use in their code well.
Comments
Post a Comment