简体   繁体   English

Java 后缀增量

[英]Java postfix increment

I understand that x=y++ is essentially shorthand for y=x and x=x+1.我知道 x=y++ 本质上是 y=x 和 x=x+1 的简写。

However, I fail to see in what scenario it can be used.但是,我看不到它可以在什么情况下使用。 Why would I increment a variable and assign its old value to a new variable.为什么我要增加一个变量并将其旧值分配给一个新变量。

If you don't find a need for something, it's best not to use it.如果你没有发现需要的东西,最好不要使用它。 Remember, don't code as cleverly as you can.请记住,不要尽可能聪明地编写代码。 Dumb it down so that you can debug it.将其哑巴,以便您可以调试它。

However, since it is a feature, of course you can make use of it.但是,既然它是一项功能,您当然可以使用它。

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
      ArrayList<Integer> l = new ArrayList<>();
      l.add(0); l.add(1); l.add(2);
      int s = 0;
      while (s<l.size()-1) {
          System.out.println(l.get(++s));
      }
    }
}

This prints 1, 2这打印 1, 2

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
      ArrayList<Integer> l = new ArrayList<>();
      l.add(0); l.add(1); l.add(2);
      int s = 0;
      while (s<l.size()) {
          System.out.println(l.get(s++));
      }
    }
}

This prints 0, 1, 2这打印 0, 1, 2

Can do it on arrays too.也可以在 arrays 上完成。 arr[i++], a[++i], a[i--], a[--i] You can do something like while(i++ > 0) too. arr[i++], a[++i], a[i--], a[--i] 您也可以执行类似 while(i++ > 0) 的操作。

It serves mainly two purposes I guess.我猜它主要有两个目的。

  1. Compress multiple extremely short lines in 1. (This is actually handy in coding tests if you use Java)在 1 中压缩多个极短的行。(如果您使用 Java,这实际上在编码测试中很方便)
  2. When you messed up and have to add 1 and subtract 1 frantically to a variable, you can use ++v, v++, --v, v-- instead of bunch of v-1, v+1, v+2, v-2, (v-1)+1... (although I think you are more likely to make a wrong program by using postfix, prefix in these cases)当你搞砸了,必须疯狂地给一个变量加 1 和减 1 时,你可以使用 ++v、v++、--v、v-- 而不是一堆 v-1、v+1、v+2、v -2, (v-1)+1... (虽然我认为在这些情况下使用后缀、前缀更有可能编写错误的程序)

If you really want to use it,.. at least avoid using 2 or more post/prefix notations on same variable on the same statement.. It is really prone to error.如果您真的想使用它,.. 至少避免在同一语句的同一变量上使用 2 个或多个后/前缀表示法.. 它真的很容易出错。 For example,例如,

x++ - ++x; // -2
++x - ++x; // -1
x++ - x++; // -1
++x - x++; // 0

I can explain why these four statements are evaluated to such results, but I wouldn't use those patterns in coding tests or any development whatsoever.我可以解释为什么这四个语句被评估为这样的结果,但我不会在编码测试或任何开发中使用这些模式。

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

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