java - Java 中的自增运算符可以使用哪些类型的操作数?
问题描述
我不知道如果我将增量运算符应用于 Java 中的表达式会发生什么。
int ai[] = new ai[10];
ai[0]++;
// ***
class Car {
public int yearMade = 0;
}
class Person {
public Car myCar = new Car();
}
Person p = new Person();
p.myCar.yearMade++;
您可以按照第一个示例显示的方式增加数组的元素吗?
你能像我在第二个例子中展示的那样增加一个类中的一个字段(我知道封装和getter/setter,我的问题是面向语法语义的)吗?
我记得 C/C++ 的时代。例如,以前 p -> x++ 存在问题。使用增量或减量时,有时需要将复杂的表达式括在括号中。
谢谢你的任何提示。
解决方案
The answer to both your questions is "Yes, you can". Both p.myCar.yearMade
and ai[0]
are variables (an instance variable and a local variable, respectively), and, thus, can be used as operands for any of these four operators.
4.12. Variables
A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3).
A variable's value is changed by an assignment (§15.26) or by a prefix or postfix ++ (increment) or -- (decrement) operator (§15.14.2, §15.14.3, §15.15.1, §15.15.2).
...
15.14.2. Postfix Increment Operator ++
At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.
推荐阅读
- python - 第一个月的虚拟变量
- perl - 使用多个参数调用 shell 命令
- c# - C# 。If (timeElapsed == seconds) 当按钮在随机秒数后被点击时,它必须改变颜色
- ruby - 用ruby中的正则表达式提取字符串中的数字
- java - JAVA鼠标事件不起作用
- django - Django 抽象模型 + DB 迁移:测试抛出“无法更改表,因为它有待处理的触发事件”
- javascript - Vue.js - 未捕获的类型错误:无法读取未定义的属性“推送”
:1:12 - python - 让 virtualenv 使用 python3
- angular - ng 服务、ng 构建、ng 构建 --prod 问题
- python - 抓取谷歌搜索结果并打印时出错