Giter Site home page Giter Site logo

Comments (4)

tomato-cc avatar tomato-cc commented on June 30, 2024

个人的理解:

// 计算 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.

tomato-cc avatar tomato-cc commented on June 30, 2024

compareUnsigned()方法一样

from learningjdk.

kangjianwei avatar kangjianwei commented on June 30, 2024

@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.

tomato-cc avatar tomato-cc commented on June 30, 2024

学到了 ,感谢解读

from learningjdk.

Related Issues (18)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.