Java's callback function rollback

Source: Internet
Author: User

Before the callback function is not very understanding, after colleagues reminded, suddenly dawned.

Today we start with the bubble sort, bubble sort everyone should know that all of the programming languages that have been exposed, the first sort you know, should be it.

Bubble sort

private static void sort (int[] a,comparator Comparator)
{
for (int i=0;i<a.length;i++)
{
for (int j=0;j<a.length-i-1;j++)
{
if (Comparator.compare (a[j],a[j+1]) ==1)
{
int TEMP=A[J];
A[J] = a[j+1];
A[J+1] = temp;
}
}
}
}

When we need to implement a sort order that is determined by the caller, the bubbling sort becomes the underlying code and cannot be tampered with, when the callback function comes in handy.

Defining interfaces

Interface comparator{
int compare (int a,int b);

}

Implementation class

Returns 0 if A>b returns 1;A<B 1;
Class Mycomparator implements comparator{

public int compare (int a, int b) {
if (a > B) {
return 1;
} else if (a < b) {
return-1;
} else {
return 0;
}
}
}

Reverse order
Class Mycomparatordesc implements comparator{
public int compare (int a, int b) {
if (a > B) {
return-1;
} else if (a < b) {
return 1;
} else {
return 0;
}
}

}

Requires a comparator interface

private static void sort (int[] a,comparator Comparator)
{
for (int i=0;i<a.length;i++)
{
for (int j=0;j<a.length-i-1;j++)
{
if (Comparator.compare (a[j],a[j+1]) ==1)
{
int TEMP=A[J];
A[J]=A[J+1];
A[j+1]=temp;
}
}
}
}

Main program

public static void Main (string[] args) {
Int[] Array=new int[]{11,22,33,44,11};
Descending arrangement

Passing a class that implements interface comparator
Sort (array,new mycomparatordesc ());
for (int arr:array)
{
System.out.print (arr+ "");
}
Ascending order
Sort (array,new mycomparator ());
for (int arr:array)
{
System.out.print (arr+ "");
}

This article is from the "about to buy wine bottle" blog, please be sure to keep this source http://22228888.blog.51cto.com/8047750/1587670

Java callback function rollback

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.