Search code examples
javaalgorithmdata-structuresqueuepriority-queue

Priority Queue Java Add Method throws syntax error and misplaced construct error


I wanted to learn how to use Priority Queues in Java for solving Algorithim based problems, I cant seem to get my priority queue to get the add method.

import java.util.PriorityQueue;

public class PQueue {

PriorityQueue pq = new PriorityQueue();
// or
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

pq.add(2);
// Java fails to recognise the add method. Moreover, on pressing spacebar + enter after pq. 

// i do not get anny suggestion for any methods supported by priority queue. 
// Is this because I am not specifying a comparator, 
// isnt integer suppose to have natural ordering by default. Need help. Feeling like a moron.


}

Solution

  • You have to write that code inside a method follow the code below

    package temp;
    import java.util.PriorityQueue;
    
    public class PQueue {
    
    
    
    
        public static void main(String[] args) {
    
            PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
            pq.add(2);
    
    
    
        }
    
    }
    

    The problem with your solution is whatever you have written is directly inside the class and so you are getting members. A class should ideally have data members and methods.

    This might help you in understanding the logic

    Class Person{

    private String name;
    private int age;
    private String address;
    
    public String getName() {
        return name;
    }
    
    
    public void setName(String name) {
        this.name = name;
    }
    
    
    
    public int getAge() {
        return age;
    
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    
    
    public String getAddress() {
        return address;
    }
    
    
    
    public void setAddress(String address) {
        this.address = address;
    }
    

    }

    All data manipulation should be done inside a method as shown in getters and settors in the above code.

    The other place to put the same code is inside a static block as shown below

    static {
    
            PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
            pq.add(2);
        }