Comments (4)
个人的理解:
// 计算 x-y的值(该方法非常另类,因为String和Integer类型的compare是比较两个值的大小,而Byte竟然是计算。。)
public static int compare(byte x, byte y) {
return x - y;
}
// 调用compare(x,y)方法。计算 x-y的值(该方法非常另类,因为String和Integer类型的compare是比较两个值的大小,而Byte竟然是计算。。)
public int compareTo(Byte anotherByte) {
return compare(this.value, anotherByte.value);
}
from learningjdk.
compareUnsigned()方法一样
from learningjdk.
@tomato-cc 嗯,这个地方其实不算错误。
第一,compare是比较函数,比较函数的要义是反映两个元素的次序。这里无论是用减号,还是用比较符号,都可以达到这种目的。
第二,按照历史惯例,compare函数通常需要返回三种值:小于0的值,0,大于0的值,以区分元素顺序。至于说大于0是10,还是100,或者是1000,都不重要,只要是大于0就行。小于0也是这个道理。所以,虽然Byte.compare中直接计算了x-y,但是它的返回值不能被理解为两个数的差值,而只能理解为两个数的次序。否则,如果按差值理解,这就偏离了该方法的本意,而且将来一旦改变了内部算法,依赖此方法的代码就要出问题了。
第三,JDK中,在比较Integer和Long时,使用了大于/小于符号,在比较Byte和Short时,使用了减号,在比较Character时,也使用了减号,这是为什么呢?原因其实非常简单,为了防止溢出...Integer和Long相减可能会溢出,而Byte、Short、Character都不会溢出,因为它们在运算时会被提升为int。
from learningjdk.
学到了 ,感谢解读
from learningjdk.
Related Issues (18)
- idea调试问题 HOT 1
- 能否在jdk源代码中添加System.out.println语句 HOT 2
- 添加忽略文件,改造成maven项目 HOT 3
- 菜菜我大概看了一下, 貌似只是注释就是将英文翻译了一下? HOT 1
- 关联jdk后,文件冲突 HOT 1
- 嗨,jdk 16 中怎么卸载自己加载的DLL HOT 1
- map和list接口里面为什么有这么多of方法 HOT 1
- maste分支拉去了代码 idea打开后 发现类缺失代码块! HOT 2
- 是不是只能用jdk15及以上的版本才行 HOT 3
- 包路径很多都报错 HOT 5
- 支持下.. HOT 1
- 源码注释显示问题? HOT 2
- 测试报错问题 HOT 10
- 可否添加JDK1.7版本 HOT 1
- 项目的时间线是不是有点问题 HOT 4
- Class类isLocalOrAnonymousClass翻译有误 HOT 1
- PackageTest01测试报错 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from learningjdk.