英文:
unable to use constructor in java
问题
我已经开始学习Java泛型,并且这是我的优先队列实现:
public class MinPQ<Key> implements Iterable<Key> {
private Key[] pq; // 在索引1到n存储项目
private int n; // 优先队列上的项目数
private Comparator<Key> comparator; // 可选比较器
public MinPQ(Key[] keys) {
n = keys.length;
pq = (Key[]) new Object[keys.length + 1];
//......
//......
}
}
这是我的主类:
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] ar = {1,2,3};
MinPQ<Integer> pq = new MinPQ<Integer>(ar);
}
}
但是在这里我得到一个错误,错误消息是**"The constructor MinPQ(int[]) is undefined"**,请问有人能帮我找到问题所在吗?
英文:
I have started learing java generics and this is my priority queue implementation:
public class MinPQ<Key> implements Iterable<Key> {
private Key[] pq; // store items at indices 1 to n
private int n; // number of items on priority queue
private Comparator<Key> comparator; // optional comparator
public MinPQ(Key[] keys) {
n = keys.length;
pq = (Key[]) new Object[keys.length + 1];
.....
.....
}
}
And this is my main class :
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] ar = {1,2,3};
MinPQ<Integer> pq = new MinPQ<Integer>(ar);
}
}
But here I get an error stating "The constructor MinPQ(int[]) is undefined" can someone please help me find the issue here ?
答案1
得分: 1
你不能在泛型中使用原始类型。只需将以下代码:
int[] ar = {1,2,3};
改为:
Integer[] ar = {1,2,3};
或者使用以下方法进行封装:
IntStream.of(ar).boxed().toArray(Integer[]::new)
基本上,你正试图将一个 int[]
传递给一个需要 Integer[]
的构造函数,这是因为 MinPQ<Integer>
的声明。因此,理论上,如果你将其声明为 MinPQ<int>
,它应该可以工作- 但正如开头所述,我们不能在泛型中使用原始类型。
英文:
You can't use primitive types with generics. Just change:
int[] ar = {1,2,3};
to:
Integer[] ar = {1,2,3};
or box it with
IntStream.of(ar).boxed().toArray(Integer[]::new)
Basically you're trying to pass an int[]
to a constructor which requires Integer[]
, because of MinPQ<Integer>
declaration. So, in tehory it should work if you declared it as MinPQ<int>
- but as stated at the beginning we can't use primitive types for generics.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论