简体   繁体   English

在Java中重载按位运算符

[英]Overloading bitwise operators in Java

I learnt that Java does not give provision to programmer to overload an operator. 我了解到Java并没有为程序员提供过载操作员的能力。 I also learnt that + is the only operator overloaded in java, 我还了解到+是java中唯一重载的运算符,

But, 但,

Operators & | 运营商& | ^ work on integral operands as bitwise operators. ^作为按位运算符处理整数操作数。

Operators & | 运营商& | ^ work on boolean operands as logical operators. ^布尔操作数作为逻辑运算符。

My question: 我的问题:

  1. Can I say that operators & ^ | 我可以说运营商& ^ | are overloaded? 超负荷?

  2. Is my jargon correct on calling these operators as bitwise operators on integral operands and logical operators on boolean operands? 我的行话是否正确调用这些运算符作为积分操作数上的按位运算符和布尔操作数上的逻辑运算符?

Because we tend to view numbers as just numbers, we often don't recognise arithmetic operators to be overloaded, despite the obvious fact that an integer division is very different from a floating point division. 因为我们倾向于将数字视为数字,所以我们常常不会认为算术运算符会过载,尽管明显的事实是整数除法与浮点除法非常不同。

So technically all the arithmetic operators are very much overloaded. 所以从技术上讲,所有算术运算符都非常过载。

The easiest way to determine what's overloaded is to imagine that instead of the + operator you had to call Operators.plus() . 确定过载的最简单方法是想象一下,您必须调用Operators.plus()而不是+运算Operators.plus() When that method needs to be overloaded to deal with different inputs, so will your operator. 当需要重载该方法来处理不同的输入时,您的操作员也将如此。

So for example when you use + in a string concatenation sense, that would be equivalent to Operators.plus(Object first, Object second) , whereas an integer addition would be covered by Operators.plus(int first, int second) , and so on. 因此,例如,当您在字符串连接意义上使用+时,这将等同于Operators.plus(Object first, Object second) ,而Operators.plus(int first, int second)将覆盖整数加法,因此上。

(However, as a thought-experiment, if we take the "relaxed" (and incorrect) view that all numbers are just numbers, we can then say the bitwise operators behave identically for all ordinal types, provided that we regard boolean as a number that is one bit long.) (但是,作为一个思想实验,如果我们采用所有数字都只是数字的“宽松”(和不正确)视图,我们可以说按位运算符对所有序数类型的行为相同,前提是我们将boolean视为数字这有点长。)

Ps: The only important thing to remember (from a practical point of view) is that | Ps:唯一要记住的(从实际的角度来看)是| and & with boolean operators don't short-circuit, while || 和| & boolean运算符不会短路,而|| and && do. &&做。 I personally wouldn't overly worry about terminology too much so long as people understand what you mean. 只要人们理解你的意思,我个人就不会过分担心术语。 As you can't overload operators in Java (as a user) anyway, it's less critical than in languages where you can. 因为无论如何你都不能在Java(作为用户)中重载运算符,所以它不如你可以使用的语言那么重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM