无法在Java中使用构造函数。

huangapple go评论100阅读模式
英文:

unable to use constructor in java

问题

我已经开始学习Java泛型,并且这是我的优先队列实现:

  1. public class MinPQ<Key> implements Iterable<Key> {
  2. private Key[] pq; // 在索引1到n存储项目
  3. private int n; // 优先队列上的项目数
  4. private Comparator<Key> comparator; // 可选比较器
  5. public MinPQ(Key[] keys) {
  6. n = keys.length;
  7. pq = (Key[]) new Object[keys.length + 1];
  8. //......
  9. //......
  10. }
  11. }

这是我的主类:

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // TODO Auto-generated method stub
  4. int[] ar = {1,2,3};
  5. MinPQ<Integer> pq = new MinPQ<Integer>(ar);
  6. }
  7. }

但是在这里我得到一个错误,错误消息是**"The constructor MinPQ(int[]) is undefined"**,请问有人能帮我找到问题所在吗?

英文:

I have started learing java generics and this is my priority queue implementation:

  1. public class MinPQ&lt;Key&gt; implements Iterable&lt;Key&gt; {
  2. private Key[] pq; // store items at indices 1 to n
  3. private int n; // number of items on priority queue
  4. private Comparator&lt;Key&gt; comparator; // optional comparator
  5. public MinPQ(Key[] keys) {
  6. n = keys.length;
  7. pq = (Key[]) new Object[keys.length + 1];
  8. .....
  9. .....
  10. }
  11. }

And this is my main class :

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // TODO Auto-generated method stub
  4. int[] ar = {1,2,3};
  5. MinPQ&lt;Integer&gt; pq = new MinPQ&lt;Integer&gt;(ar);
  6. }
  7. }

But here I get an error stating "The constructor MinPQ(int[]) is undefined" can someone please help me find the issue here ?

答案1

得分: 1

你不能在泛型中使用原始类型。只需将以下代码:

  1. int[] ar = {1,2,3};

改为:

  1. Integer[] ar = {1,2,3};

或者使用以下方法进行封装:

  1. IntStream.of(ar).boxed().toArray(Integer[]::new)

基本上,你正试图将一个 int[] 传递给一个需要 Integer[] 的构造函数,这是因为 MinPQ<Integer> 的声明。因此,理论上,如果你将其声明为 MinPQ<int>,它应该可以工作- 但正如开头所述,我们不能在泛型中使用原始类型。

英文:

You can't use primitive types with generics. Just change:

  1. int[] ar = {1,2,3};

to:

  1. Integer[] ar = {1,2,3};

or box it with

  1. IntStream.of(ar).boxed().toArray(Integer[]::new)

Basically you're trying to pass an int[] to a constructor which requires Integer[], because of MinPQ&lt;Integer&gt; declaration. So, in tehory it should work if you declared it as MinPQ&lt;int&gt; - but as stated at the beginning we can't use primitive types for generics.

huangapple
  • 本文由 发表于 2020年5月30日 04:45:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/62094338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定