在Java中创建通用数组 [英] Generic array creation in java

查看:83
本文介绍了在Java中创建通用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:



Java如何:创建通用数组

我正在尝试创建一个通用类型的类。这是我的类文件。

  public class TestClass< T>实现AbstractDataType< T> {

T [] contents;

public TestClass(int length){
this.contents =(T [])new Object [length];


但是内容只有从对象类。我如何为内容创建一个抽象数组?

解决方案> 你能做的最好。如果有办法, ArrayList 可能会这样做(第132行: http://www.docjar.com/html/api/java/util/ArrayList.java.html

但是当你说内容刚刚有从Object类继承的方法时,我假设你的意思是你只能访问 toString 等于,并且我猜这是主要问题。那是因为你没有告诉编译器什么是 T 实例。如果你想从特定的接口或类型访问方法,你需要在 T 上放置一个类型约束。



下面是一个例子:

$ p $ interface Foo {
int getSomething();
void setSomethingElse(String somethingElse);
}

public class TestClass< T extends Foo>实现AbstractDataType< T> {
T []内容;

public TestClass(int length){
this.contents =(T [])new Object [length];
}

public void doSomethingInteresting(int index,String str){
T obj = contents [index];
System.out.println(obj.getSomething());
obj.setSomethingElse(str);






$ b

现在你可以访问从那些继承的方法以外的方法 Object


Possible Duplicate:
Create instance of generic type in Java?
Java how to: Generic Array creation

I am trying to create a create a class of generic type. This is my class file.

public class TestClass<T> implements AbstractDataType<T>{

    T[] contents;

    public TestClass(int length) {
        this.contents = (T[])new Object[length];
    }
}

But the contents have just have the methods inherited from the Object class. How can I create an abstract array for contents ?

解决方案

As far as initializing contents, I think what you have is the best you can do. If there way a way, ArrayList would probably do it (line 132: http://www.docjar.com/html/api/java/util/ArrayList.java.html)

But when you say "the contents have just have the methods inherited from the Object class", I'm assuming you mean that you can only access methods like toString and equals when you are working with a T instance in your code, and I'm guessing this is the primary problem. That's because you're not telling the compiler anything about what a T instance is. If you want to access methods from a particular interface or type, you need to put a type constraint on T.

Here's an example:

interface Foo {
  int getSomething();
  void setSomethingElse(String somethingElse);
}

public class TestClass<T extends Foo> implements AbstractDataType<T> {
  T[] contents;

  public TestClass(int length) {
    this.contents = (T[])new Object[length];
  }

  public void doSomethingInteresting(int index, String str) {
    T obj = contents[index];
    System.out.println(obj.getSomething());
    obj.setSomethingElse(str);
  }
}

So now you can access methods other than those inherited from Object.

这篇关于在Java中创建通用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆