Dav*_*ave 6 java arrays generics
所以我知道你不能"轻松地"在Java中创建一个泛型类型的数组(但你可以创建集合).我最近遇到了一个需要二维对象数组(即Generic)的情况.这是一个"粗略"的概念,它看起来像什么(不完整,但我想尽可能简短):
class Outer<T> {
private Foo[][] foo;
abstract class Foo extends Blah<T> {
public List<T> getContents ();
}
abstract class Bar extends Foo {
...
}
}
Run Code Online (Sandbox Code Playgroud)
所以代码中的某个地方我需要一个数组:
foo = new Foo[width][height];
Run Code Online (Sandbox Code Playgroud)
(我们知道不可能发生).但是,我试过这个:
foo = (Foo[][])Array.newInstance (Foo.class, new int[]{getWidth (), getHeight ()});
Run Code Online (Sandbox Code Playgroud)
虽然我不得不压制警告但编译器接受了.我想我的问题是"这会扼杀我在萌芽状态某处行?的成员'foo’被永远不会暴露于外(虽然类型Foo和Bar是).我知道这是丑陋的,但它肯定工程和救了我不必创建一些其他的"psedu-杂牌"的或许会导致类覆盖"外"类更多的麻烦.在此先感谢!
这更接近我实际做的事情; 当然,我实现了Map类中有许多支持方法和其他逻辑,我为了简洁起见而遗漏了这些方法.
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
interface Cell<T> {
public void add (T t);
public boolean remove (T t);
public List<T> getAll ();
public Map<T> getMap ();
}
class Map<T> {
protected BaseCell map[][];
public abstract class BaseCell implements Cell<T> {
private List<T> contents;
public BaseCell () {
this.contents = new ArrayList<T> ();
}
public void add (T t) {
this.contents.add (t);
}
public boolean remove (T t) {
return this.contents.remove (t);
}
public List<T> getAll () {
return this.contents;
}
public Map<T> getMap () {
return Map.this;
}
abstract public boolean test ();
}
public class SpecialCell extends BaseCell {
@Override
public boolean test() {
return true;
}
}
public class SpecialCell2 extends BaseCell {
@Override
public boolean test() {
return false;
}
}
@SuppressWarnings("unchecked")
public Map (int width, int height) {
this.map = (BaseCell[][])Array.newInstance(BaseCell.class, new int[] {width, height});
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (Math.random() < .5) {
this.map[x][y] = new SpecialCell ();
} else {
this.map[x][y] = new SpecialCell2 ();
}
}
}
}
public BaseCell getCellAt (int x, int y) {
return this.map[x][y];
}
}
public class Junk {
/**
* @param args
*/
public static void main(String[] args) {
class Occupant {
}
Map<Occupant> map = new Map<Occupant> (50, 50);
map.getCellAt(10, 10).add(new Occupant ());
map.getCellAt(10, 10).getMap ();
for (int y = 0; y < 50; y++) {
for (int x = 0; x < 50; x++) {
System.out.print (map.getCellAt (x, y).test () ? "1" : "0");
}
System.out.println ();
}
}
}
Run Code Online (Sandbox Code Playgroud)
你所做的事情是安全的,因为你正在控制未暴露的map。您可能应该将其设置为私有而不是受保护,否则扩展类可能会错误地操作它。您可以通过转换为运行时检查来消除编译器警告,如下所示:
this.map = BaseCell[][].class.cast(Array.newInstance(BaseCell.class,
new int[] { width, height }));
Run Code Online (Sandbox Code Playgroud)
然后,如果在稍后的某个时刻,代码可能以不兼容的方式更改,而编译器警告会屏蔽掉,那么它至少会在构建map. 当然请记住,泛型只是在编译时被删除。