問題を再構成し、それが役立つかどうかを確認してください。 1は、このようなAPIを必要とします
interface BitMap {
/**
* Set or clear a flag at the given coordinates.
*/
void set(int x, int y, boolean flag);
/**
* Test whether a given coordinate is true or false.
*/
boolean get(int x, int y);
}
あなたが本当に例えば内部表現—気にしないのであれば、あなたはで構成バイトのシーケンスを想定し、既存のAPIに公開する必要はありません特定の方法—私はシンプルで堅牢な表現としてBitSet
を使用することをお勧め:
final class BitMapImpl
implements BitMap
{
private final int w, h;
private final BitSet bits;
BitMapImpl(int w, int h)
{
if (w < 0)
throw new IllegalArgumentException("w < 0: " + w);
if (h < 0)
throw new IllegalArgumentException("h < 0: " + h);
this.w = w;
this.h = h;
bits = new BitSet(w * h);
}
@Override
public void set(int x, int y, boolean flag)
{
check(x, y);
int i = y * w + x;
bits.set(i, flag);
}
@Override
public boolean get(int x, int y)
{
check(x, y);
int i = y * w + x;
return bits.get(i);
}
private void check(int x, int y)
{
if (x < 0)
throw new IllegalArgumentException("x < 0: " + x);
if (x >= w)
throw new IllegalArgumentException("x >= w: " + x);
if (y < 0)
throw new IllegalArgumentException("y < 0: " + y);
if (y >= h)
throw new IllegalArgumentException("y >= h: " + y);
}
@Override
public String toString()
{
StringBuilder str = new StringBuilder();
hf(str);
for (int y = 0; y < h; ++y) {
str.append('|');
for (int x = 0; x < w; ++x)
str.append(get(x, y) ? '*' : ' ');
str.append('|');
str.append(System.lineSeparator());
}
hf(str);
return str.toString();
}
private void hf(StringBuilder str)
{
str.append('+');
for (int x = 0; x < w; ++x)
str.append('-');
str.append('+');
str.append(System.lineSeparator());
}
/* Demonstrate usage */
public static void main(String... argv)
{
BitMap map = new BitMapImpl(2, 12);
for (int y : new int[]{1, 2, 4, 8})
for (int x = 0; x < 2; ++x)
map.set(x, y, true);
map.set(1, 6, true);
map.set(1, 10, true);
System.out.println(map);
}
}
あなたはインデックスを記述する方法は、「リトルエンディアン」の一種です。つまり、各行を16ビット値と考えると、最上位ビットはビット0です。これは、既存のコードとの相互運用性に必要ですか?そうでない場合は、異なる内部表現を使用すると操作が少しきれいになるためです。 – erickson
これはどのように動作するのかのコードタイプの例を教えてください。 – user5438578
はXYの問題のようです(ちょっと意図したように) – Alnitak