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

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

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&lt;Key&gt; implements Iterable&lt;Key&gt; {
   private Key[] pq;                    // store items at indices 1 to n
   private int n;                       // number of items on priority queue
   private Comparator&lt;Key&gt; 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&lt;Integer&gt; pq = new MinPQ&lt;Integer&gt;(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&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:

确定