Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is java question Is there another form of these code? that create similar o

ID: 3898113 • Letter: T

Question

This is java question

Is there another form of these code? that create similar output.

these are the code:

Comparator<show> s = new Comparator<show>(){ // this part i am confuse why instead of using ; i am using {

public int compare(show first, show second){

return first.getName().compareTo(second.getName());

}

}; // this one too why they need to have ; after }

also this code why it seem that the compare method is issite the Collection.sort

Collections.sort(show, new Comparator<show>(){
public int compare(show s1, show s2){
return s1.getName().compareTo(s2.getName());
}  
}
);

Explanation / Answer

Hi,

This feature is known as "Anonymous classes" and is used to make the code shorter.

In your example, Comparator is an interface. right?

Usually, you would have to write a new class that implements Comparator and then create an instance of that class.

This code will be verbose.

Instead of writing this verbose code, you can follow this new syntax

InterfaceName var = new InterfaceName() {
  
//Implement some method here

};


Note that this is equivalent to
1. Writing a class
2. and Creating an object

at the same time.

Refer to Java tutorial for more information
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html


Your second query is same as the first one except that you are passing it to method that expects a Comparator instance.

You would also written it as
Collections.sort(show, s);

the variable "s" is from your first Comparator declaration

I hope, now you have better understanding. Revert to me if you need more explanation.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote