Search code examples
javapriority-queueternary-operator

Java: How to access an instance variable in a ternary operator?


This is the ListNode class:

  public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
  }

I am trying to initialize a PriorityQueue like this:

PriorityQueue<ListNode> heap = new PriorityQueue(lists.length,
            (l1, l2) -> l1.val < l2.val ? -1 :
                        l1.val == l2.val ? 0 :
                        1);

But I am getting "cannot find symbol: variable val". What is the proper way to do this? I've tried casting l1 and l2 as ListNode's, but this does not do anything.

Edit: Why does this work?

    PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
            @Override
            public int compare(ListNode o1,ListNode o2){
                if (o1.val<o2.val)
                    return -1;
                else if (o1.val==o2.val)
                    return 0;
                else 
                    return 1;
            }
        });

Solution

  • You are missing the diamond operator on the right hand side which made the compiler not infer the argument type as ListNode (It inferred it as an Object and hence you cannot access val)

    Try this

     PriorityQueue<ListNode> heap = new PriorityQueue<>(lists.length,
                (l1, l2) -> l1.val < l2.val ? -1 :
                        l1.val == l2.val ? 0 :
                                1);
    

    My initial answer:

    If you have your PriorityQueue declaration in a different package (from the one where ListNode is declared):

    It has nothing to do with the ternary opeator. The variable val is package-private. Making it public will solve the issue but it is not a good practice. Instead, add a getter for it and make the instance variables private (unless you have a reason for making them package-private)

    public int getVal() {
        return val;
    }
    
    
    PriorityQueue<ListNode> heap = new PriorityQueue<>(lists.length,
            (l1, l2) -> l1.getVal() < l2.getVal() ? -1 :
                        l1.getVal() == l2.getVal() ? 0 :
                        1);