讓我重新解決問題,看看它是否有幫助。假設一個人需要這樣的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