当前位置:网站首页>浅谈string中的compareTo方法
浅谈string中的compareTo方法
2022-07-29 10:52:00 【51CTO】
今天看了一篇gitchat的文章,标题是 聊聊 Java String 源码的排序算法,从中有所感悟和思考,因此打算总结下自己看的过程中的收获
一,java.lang.Comparable 接口
Comparable 接口强制了实现类对象列表的排序。其排序称为自然顺序,其 compareTo 方法,称为自然比较法
如果用this代表当前调用该compareTo方法的对象,obj是方法传入参数
则:
Comparable接口的compareTo是一种内比较,即支持跟当前对象比较
二,java.util.Comparator 接口
Comparator可以认为是是一个外比较器,一个对象不支持自己和自己比较(没有实现Comparable接口),但是又想对两个对象进行比较
比较逻辑
三,聊聊string中的compareTo方法
String中实现的是Comparable接口来为String对象作出比较逻辑
先看一段示例
结果:
再结合上边示例看看String中对compareTo方法的实现
所以从上面的源码中可以看到,string中的compareTo逻辑大概可以整理为
- 字符串前面部分的每个字符完全一样,返回:后面两个字符串长度差;
- 字符串前面部分的每个字符存在不一样,返回:出现不一样的字符 ASCII 码的差值。
- 字符串的每个字符完全一样,返回 0;
在String内部还有个静态内部类CaseInsensitiveComparator也实现了该接口
该重写的接口方法是String对象的大小写不敏感比较方法
边栏推荐
- StarRocks 技术内幕:实时更新与极速查询如何兼得
- 牛客网刷题
- Create PHP message board system with kubernetes
- 学习R语言这几本电子书就够了!
- Alibaba P8 broke out this interview guide for big factories. After reading it, the salary soared by 30K!
- Drawing box and ellipse of WPF screenshot control (IV) "imitating wechat"
- Drunken driving alarm system based on stm32
- Detailed arrangement of JVM knowledge points (long text warning)
- ES6-箭头函数this指向
- Leetcode binary tree series -- 144. Preorder traversal of binary trees
猜你喜欢

Kunlunbase instruction manual (II) best practices for peer-to-peer deployment

Object storage

VMware: use commands to update or upgrade VMware esxi hosts

学习R语言这几本电子书就够了!

The heavyweight foundation awarded platinum, gold and silver donors

WPF 截图控件之绘制方框与椭圆(四) 「仿微信」

Alibaba P8 broke out this interview guide for big factories. After reading it, the salary soared by 30K!

How to synchronize when the primary and sub warehouses are modified?

周鸿祎:360是世界上最大的安全大数据公司

重磅 | 开放原子校源行活动正式启动
随机推荐
ES6-箭头函数this指向
主子仓库都修改,如何进行同步?
What are the compensation standards for hospital misdiagnosis? How much can the hospital pay?
Error: Protobuf syntax version should be first thing in file
R 语言 Monte Carlo方法 和平均值法 计算定积分, 考虑随机投点法,计算在置信度0.05, 要求为ϵ=0.01 , 所需要的试验次数
Site data collection -scrapy usage notes
LeetCode_278_第一个错误的版本
AI模型风险评估 第2部分:核心内容
Steps of project explanation in interview
Use tidymodels to solve the binary logistic model
Regular expression matching URL
The 2022 open atom global open source summit opened in Beijing
Data visualization design guide (information chart)
阿里架构师耗时一年整理的《Lucene高级文档》,吃透你也是大厂员工!
Introduction to distributed scheduling xxl-job features
The heavy | open atomic school source activity was officially launched
数据可视化设计指南(信息图表篇)
R package pedquant realizes stock download and financial quantitative analysis
Spark efficient data analysis 02, basic knowledge 13
Research on the realization of linear gradient circular progress bar