Java中NOT运算符(!)结合方法的工作原理解析
为什么在FailSoftArray的put方法调用中必须使用NOT运算符(!)?
示例代码
class FailSoftArray { private int a[]; private int errval; public int length; public FailSoftArray(int size, int errv) { a = new int[size]; errval = errv; length = size; } public int get(int index) { if(indexOK(index)) return a[index]; return errval; } public boolean put(int index, int val) { if(indexOK(index)) { a[index] = val; return true; } return false; } private boolean indexOK(int index) { if(index >= 0 & index < length) return true; return false; } } public class TestMethod { public static void main(String[] args) { // 原代码中FailSoftArray333为笔误,修正为FailSoftArray FailSoftArray fs = new FailSoftArray(5, -1); int x; System.out.println("\nError access message."); for(int i = 0; i < (fs.length * 2); i++) if(!fs.put(i, i*10)) System.out.println("Index " + i + " outside the range of the array"); for(int i =0; i < (fs.length * 2); i++) { x = fs.get(i); if(x != -1) System.out.print(x + " "); else System.out.println("Index " + i + " outside the range of the array"); } } }
问题核心
你困惑的是这段代码中!的必要性:
System.out.println("\nError access message."); for(int i = 0; i < (fs.length * 2); i++) if(!fs.put(i, i*10)) System.out.println("Index " + i + " outside the range of the array");
使用!时的正确输出
Error access message. Index 5 outside the range of the array Index 6 outside the range of the array Index 7 outside the range of the array Index 8 outside the range of the array Index 9 outside the range of the array 0 10 20 30 40 Index 5 outside the range of the array Index 6 outside the range of the array Index 7 outside the range of the array Index 8 outside the range of the array Index 9 outside the range of the array
不使用!时的错误输出
Error access message. Index 0 outside the range of the array Index 1 outside the range of the array Index 2 outside the range of the array Index 3 outside the range of the array Index 4 outside the range of the array 0 10 20 30 40 Index 5 outside the range of the array Index 6 outside the range of the array Index 7 outside the range of the array Index 8 outside the range of the array Index 9 outside the range of the array
详细解释
1. put方法的返回值语义
先明确put方法的设计逻辑:
- 当传入的索引合法(
indexOK返回true),方法完成数组赋值,返回**true**,代表操作成功。 - 当索引不合法(越界),方法不执行赋值,返回**
false**,代表操作失败。
2. NOT运算符!的工作机制
!是Java的布尔取反运算符,作用很直接:
- 对
true取反得到false - 对
false取反得到true
3. 使用!的必要性
我们的需求是当put操作失败(索引越界)时打印错误信息:
- 索引越界时,
fs.put(...)返回false,!false等于true,满足if条件,触发错误打印逻辑,这完全符合需求。 - 如果去掉
!,条件变成fs.put(...):索引合法时fs.put(...)返回true,会错误地打印“索引越界”;索引越界时返回false,反而不会触发打印,完全和需求逻辑相反。
4. 对方法的影响
!仅对put方法的返回值做逻辑取反,不会改变put方法本身的执行逻辑:
- 无论加不加
!,put都会正常判断索引合法性,合法就赋值,不合法就跳过。 !只影响后续的分支逻辑(是否执行错误打印),不会修改put的内部行为。
内容的提问来源于stack exchange,提问作者b3jf
相关产品推荐
相关产品推荐

