Home > Mobile >  Getting Error from Generic Class and Comparator
Getting Error from Generic Class and Comparator

Time:03-18

I have encountered some issues while coding my generic class with a comparator. I have a class called PQ that takes in a Comparator. This is my class PQ.

import java.util.List;
import java.util.ArrayList;
  
class PQ<T extends Comparable<T>> {
    private final ArrayList<T> queue;

    PQ(Comparator<T> cmp){
        this.queue = new ArrayList<T>();
    }

    PQ(ArrayList<T> queue) {
        this.queue = queue;
    }

So the error happens when the question requires my code to take in

Comparator<Object> c = (x, y) -> x.hashCode() - y.hashCode()
pq = new PQ<String>(c)

This error pops up.

|  Error:
|  cannot find symbol
|    symbol:   variable pq
|  pq = new PQ<String>(c)
|  ^^
|  Error:
|  no suitable constructor found for PQ(java.util.Comparator<java.lang.Object>)
|      constructor PQ.PQ(java.util.Comparator<java.lang.String>) is not applicable
|        (argument mismatch; java.util.Comparator<java.lang.Object> cannot be converted to java.util.Comparator<java.lang.String>)
|      constructor PQ.PQ(ImList<java.lang.String>) is not applicable
|        (argument mismatch; java.util.Comparator<java.lang.Object> cannot be converted to ImList<java.lang.String>)
|  pq = new PQ<String>(c)
|       ^---------------^

Would really appreciate any help! Thanks!

CodePudding user response:

pq = new PQ<String>(c) // T is String

In this way, you specified the generic parameters T is String, so those two constructors will accept Comparator<String> or ImList<String>.You just give the wrong parameter Comparator<Object>.

pq = new PQ<Object>(c) // T is Object, any subclass can be accept

You can change to this get it worked.

  • Related