登录
  • #刷题
  • #学java/c#

为啥studentComparator class不能写在里面...

akdhfikbk
675
5
楼主在练PQ问题,深受Comparator class困扰,

来个技术流问题:StudentComparator这个class放在comparatorGeeksfGeeks这个class里面就会出现

PriorityQueue<Student> pq = new PriorityQueue<Student>(5, new StudentComparator());这个问题

报错信息是Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type comparatorGeeksfGeeks is accessible. Must qualify the allocation with an enclosing instance of type comparatorGeeksfGeeks (e.g. x.new A() where x is an instance of comparatorGeeksfGeeks).

看不太懂耶...

所以为啥非要拿出来才可以?下面是拿出来后才正确的代码

[mw_shl_code=java,true]class StudentComparator implements Comparator<Student> {

// Overriding compare()method of Comparator

// for descending order of cgpa

public int compare(Student s1, Student s2) {

if (s1.cgpa < s2.cgpa)

return 1;

else if (s1.cgpa > s2.cgpa)

return -1;

return 0;

}

}

class Student {

public String name;

public double cgpa;

// A constructor

public Student(String name, double cgpa) {

this.name = name;

this.cgpa = cgpa;

}

public String getName() {

return name;

}

}

public class comparatorGeeksfGeeks {





// Java program to demonstrate working of

// comparator based priority queue constructor

public static void main(String[] args) {[br]
Scanner in = new Scanner(System.in);

// Creating Priority queue constructor having

// initial capacity=5 and a StudentComparator instance

// as its parameters

PriorityQueue<Student> pq = new PriorityQueue<Student>(5, new StudentComparator());

// Invoking a parameterized Student constructor with

// name and cgpa as the elements of queue

Student student1 = new Student("Nandini", 3.2);

// Adding a student object containing fields

// name and cgpa to priority queue

pq.add(student1);

Student student2 = new Student("Anmol", 3.6);

pq.add(student2);

Student student3 = new Student("Palak", 4.0);

pq.add(student3);

// Printing names of students in priority order,poll()

// method is used to access the head element of queue

System.out.println("Students served in their priority order");

while (!pq.isEmpty()) {

System.out.println(pq.poll().getName());

}

}

}[/mw_shl_code]
5条回复
热度排序

发表回复