++i 与 i++ 区别及踩过的坑

来源:互联网 发布:淘宝网hd下载 编辑:程序博客网 时间:2024/06/05 21:08

++i 与i++的区别是前者是先运算再取值,后者是先取值在运算

Section1

public class Test {    public static void main(String args[]){        int i = 0;        CalculateBean test = new CalculateBean();        test.changeIndex(i++);    }}
public class CalculateBean {    public void changeIndex(int index){        System.out.println("the value is "+index);    }}

问,打印结果是0还是1?
我们run一下,
答案是
the value is 0
==============================================================
Section2
修改一下
public static void main(String args[]){    int i = 0;    CalculateBean test = new CalculateBean();    for (int k = 0;k<10;k++){        test.changeIndex(i++);    }}
打印结果是
the value is 0the value is 1the value is 2the value is 3the value is 4the value is 5the value is 6the value is 7the value is 8the value is 9
-----------------------------------------
虽然在传入参数的时候i++了,但是仍然是从0开始的;
Section3
i++和++i的区别虽然比较简单,但是在开发的时候有的时候不注意,就有可能用错,
而且这种错误不注意还发现不了。。。
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {    super.onViewCreated(view, savedInstanceState);    loadData(currentPage);    initLoadMoreListener();
.......
protected int currentPage = 1;private void doLoadMore() {    loadData(currentPage++);}

像最近遇到的这个bug,page 1 加载了两次,就是由于这个地方没有注意造成的。


原创粉丝点击