How to Increment a class Integer references value in java from another method

后端 未结 10 626
攒了一身酷
攒了一身酷 2020-12-09 02:29
package myintergertest;

/**
 *
 * @author Engineering
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void          


        
10条回答
  •  遥遥无期
    2020-12-09 03:04

    Side note: In my humble opinion, writing n++ on an Integer object is extremely misleading. This relies on a feature of Java called "autoboxing" where it converts primitives to their corresponding boxing objects -- like int to Integer or boolean to Boolean -- automatically and without warning. Frankly I think it's a bad feature. Yes, sometimes it makes your life simpler by automatically doing a handy conversion for you, but it can also do conversions that you did not intend and do not realize are happening, with unintended side effects.

    Anyway, there are two ways to accomplish what you are apparently trying to do:

    One: Have the increment function return a new Integer with the updated value. Like:

       public Integer increment(Integer n)
        {
          Integer nPlus=Integer.valueOf(n.intValue()+1);
          return nPlus;
        }
    

    then call it with:

    Integer n=Integer.valueOf(0);
    n=increment(n); // now n==1
    n=increment(n); // now n==2
    

    Etc.

    Two: Create your own class that resembles Integer but that is mutable. Like:

    class MutableInteger
    {
      int value;
      public MutableInteger(int n)
      {
        value=n;
      }
      public void increment()
      {
        ++value;
      }
      ... whatever other functions you need ...
    }
    

    Of course the big catch to this is that you pretty much have to re-invent the Integer class.

提交回复
热议问题