通用类中的java通用转换 [英] java generic casting in generic classes

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

问题描述

我在写一个通用的最大堆的简单实现。如果我写了

  public class FastMaxHeap< T> {

T [] data;
int size;

static final int HEAP_SIZE = 10000;

@SuppressWarnings(unchecked)
public FastMaxHeap(){
data =(T [])new Object [HEAP_SIZE];
size = 0;
}
}

编译。现在要实际实现堆,即写入maxHeapify(),我需要能够比较两个T。先验似乎是可能的一种选择是告诉编译器T实现了Comparable。但是,如果我键入替换< T>与< T实现Comparable>编译器抱怨 - 我该怎么做?



或者,我可以定义一个类

  public class HasValue {

int value;

公共HasValue(int值){
this.value = value;
}

}

理论上我应该能够比较两个HasValue对象,如x.value> y.value。但是如果我输入

  public class FastMaxHeap< T extends HasValue> {

T [] data;
int size;

static final int HEAP_SIZE = 10000;

@SuppressWarnings(unchecked)
public FastMaxHeap(){
data =(T [])new Object [HEAP_SIZE];
size = 0;
}
}

现在我得到一个ClassCastException。这里发生了什么? Java泛型伤害了我的大脑。

解决方案

在第一种情况下 T extends Object 在运行时擦除为 Object 在第二种情况下 T扩展了HasValue 被清除为 HasValue ,因此您需要拥有。

  data =(T [])new HasValue [HEAP_SIZE]; 

恕我直言,Java是不允许 new T [HEAP_SIZE ] 去做你必须做的事情。


I'm writing a simple implementation of a generic max heap. If I write

public class FastMaxHeap<T>{

  T[] data;
  int size;

  static final int HEAP_SIZE = 10000;

  @SuppressWarnings("unchecked")
  public FastMaxHeap(){
    data = (T[]) new Object[HEAP_SIZE];
  size = 0;
  }
}

it compiles. Now to actually implement the heap, i.e. write maxHeapify(), I need to be able to compare two T's. One option that a priori seems possible would be to tell the compiler that T implements Comparable. But if I type replace < T > with < T implements Comparable > the compiler complains -- how can I do this?

Alternatively, I could define a class

public class HasValue{

  int value;

  public HasValue(int value){
        this.value = value;
  }

}

and in theory I should then be able to compare two HasValue objects like x.value > y.value. But if I type

public class FastMaxHeap<T extends HasValue>{

  T[] data;
  int size;

  static final int HEAP_SIZE = 10000;

  @SuppressWarnings("unchecked")
  public FastMaxHeap(){
    data = (T[]) new Object[HEAP_SIZE];
  size = 0;
  }
}

I now get a ClassCastException. What is going on here? Java generics hurt my brain.

解决方案

In the first case T extends Object which is erased to Object at runtime.

In the second case T extends HasValue is erased to HasValue so you need to have.

data = (T[]) new HasValue[HEAP_SIZE];

IMHO It is needlessly pedantic that Java doesn't allow new T[HEAP_SIZE] to do what you have to do anyway.

这篇关于通用类中的java通用转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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