Java- for loop using << operator -
i'm stuying code , don't understand line does: [(y << 3) + x]
(int y = 0; y <= 7; ++y) { (int x = 0; x <= 7; ++x) { final string piececode = piececodes[(y << 3) + x]; if (piececode.length() != 2) throw new illegalargumentexception(); if (!piececode.equals("--")) { pieces[((7 - y) << 3) + x] = checkerspiece.valueof(piececode.charat(0), piececode.charat(1)); } } }
(y << 3) means bit shifting 3 times left. it's same multiplying 2^3 = 8. so, whole expression (y << 3) + x becomes y * 8 + x.
it should written in form y * 8 + x, because it's more readable , there no performance gain. premature optimization root of evil. it's better left such micro optimizations compiler (or jvm).
moreover, board size stored in constant, have in 1 place:
final int size = 8; // ... (int y = 0; y < size; y++) { (int x = 0; x < size; x++) { final string piececode = piececodes[y * size + x]; y * 8 + x iterating on (logically) 2d table 8 rows , columns, stored 1d, 64 cells.
as final remark, point out, in given code piececodes array of strings... in fact, it's array of piece codes. not some strings. now, "--" works magic state , nobody except programmer knows, means. if (piececode.length() != 2) looks bad. so, there should object piececode , array declared piececode[] piececodes. in piececode can implement proper equals() method. if piececode state, can enum. example empty, white_pawn, white_queen, black_pawn, black_queen. comparing strings not fast comparing enums. have watch out write equals(), instead of ==.
Comments
Post a Comment