没有阅读规范(不 - 我的意思是,只是 不!):4,294,967,296 x 4,294,967,296 数组显然是一个高度理论化的构造,并且这些“数组条目”中只有一小部分可以并将永远被使用。
除此之外:无论您使用数组还是任何其他集合,您都会遇到索引问题:数组索引只能是 int 值,但 4,294,967,296 是 Integer.MAX_VALUE 的两倍大(有在 Java 中没有无符号整数)。
但是,表示这种“无限大”稀疏二维数组的一种方法是将长值对(x 和 y 坐标)映射到数组条目的映射。大致是这样的:
import java.util.HashMap;
import java.util.Map;
interface Space<T>
{
void set(long x, long y, T value);
T get(long x, long y);
}
class DefaultSpace<T> implements Space<T>
{
private final Map<LongPair, T> map = new HashMap<LongPair, T>();
@Override
public void set(long x, long y, T value)
{
LongPair key = new LongPair(x,y);
if (value == null)
{
map.remove(key);
}
else
{
map.put(key, value);
}
}
@Override
public T get(long x, long y)
{
return map.get(new LongPair(x,y));
}
}
class LongPair
{
private final long x;
private final long y;
LongPair(long x, long y)
{
this.x = x;
this.y = y;
}
@Override
public String toString()
{
return "("+x+","+y+")";
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (x ^ (x >>> 32));
result = prime * result + (int) (y ^ (y >>> 32));
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LongPair other = (LongPair) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}