博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Java学习笔记】实现Comparator接口来进行字符串逆向排序
阅读量:7255 次
发布时间:2019-06-29

本文共 1861 字,大约阅读时间需要 6 分钟。

作者:

出处:

// Create a Comparator that returns the outcome

// of a reverse string comparison.
class RevStrComp implements Comparator<String> {
  // Implement the compare() method so that it
  // reverses the order of the string comparison.
  public int compare(String strA, String strB) {// Compare strB to strA, rather than strA to strB.
return strB.compareTo(strA);
  }
}

// Sort an array of strings in reverse order.

import java.util.*;
// Create a Comparator that returns the outcome
// of a reverse string comparison.
class RevStrComp implements Comparator<String> {
  // Implement the compare() method so that it
  // reverses the order of the string comparison.
  public int compare(String strA, String strB) {
    // Compare strB to strA, rather than strA to strB.
    return strB.compareTo(strA);
  }
}
// Demonstrate the reverse string comparator.
class RevStrSort {
  public static void main(String args[]) {
    // Create a sample array of strings.
    String strs[] = { "dog", "horse",  "zebra", "cow", "cat" };
    // Show the initial order.
    System.out.print("Initial order: ");
    for(String s : strs)
      System.out.print(s + " ");
    System.out.println("/n");
    // Sort the array in reverse order.
    // Begin by creating a reverse string comparator.
    RevStrComp rsc = new RevStrComp();

    // Now, sort the strings using the reverse comparator.

    Arrays.sort(strs, rsc);
    // Show the reverse sorted order.
    System.out.print("Sorted in reverse order: ");
    for(String s : strs)
      System.out.print(s + " ");
    System.out.println("/n");
    // For comparison, sort the strings in natural order.
    Arrays.sort(strs);
    // Show the natural sorted order.
    System.out.print("Sorted in natural order: ");
    for(String s : strs)
      System.out.print(s + " ");
    System.out.println("/n");
  }
}

输出为:

Initial order: dog horse zebra cow cat

Sorted in reverse order: zebra horse dog cow cat
Sorted in natural order: cat cow dog horse zebra

 

作者:

出处:

转载地址:http://knzdm.baihongyu.com/

你可能感兴趣的文章
【软件解决】解决VS环境中出现虚线问题
查看>>
laravel 实现增 与查
查看>>
一种排序
查看>>
Linux实战教学笔记44:NoSQL数据库开篇之应用指南
查看>>
springmvc(2)处理器设配器和映射器
查看>>
PAT 1003
查看>>
switch gnome-terminal tabs
查看>>
怎样理解Functor与Monad
查看>>
DRF教程4-视图集和路由类
查看>>
javascript向上滚动(放上鼠标就停)
查看>>
python的编码问题
查看>>
获取下拉框的值
查看>>
windows server2012 R2 本地策略编辑
查看>>
数据结构与算法(3)图
查看>>
VB Script 如何使用动态数组分配
查看>>
WRMPS经典Cookie欺骗漏洞批量拿下shell-黑客博客
查看>>
SQLServer异步调用,批量复制
查看>>
复习装饰器
查看>>
倍增算法
查看>>
outerHTML
查看>>