【问题标题】:Returns the int unique返回 int 唯一值
【发布时间】:2019-07-09 05:43:52
【问题描述】:

我需要返回此商品的 int 唯一 SKU 编号

public class SKU { 
    private static int pkey_next = 123018;
    public int getSKU() { // Returns the int unique SKU number for this item
        return pkey_next++;
    }
}

SKU 类必须有一个private static int pkey_next = 123018;,它将定义我们商店中商品的起始“主键”标识号。既然从123018开始,我应该得到System.out.println(three.getSKU()); // 123020.

我现在收到 123018。

【问题讨论】:

  • 你有问题吗?
  • 您应该如何从System.out.println(three.getSKU()); 获得123020
  • @SudhirOjha 教授提供测试代码
  • 这个方法每次调用都会返回一个不同的数字,而不是每个实例都返回一个不同的数字。
  • 请在您的问题中包含所有必要的信息。不要让每个人都尝试和猜测。

标签: java unique


【解决方案1】:

我认为您正在尝试在获得独特价值的同时实现原子性。如果是,那么您可以尝试以下方法

public class SKU {

    private static final AtomicInteger PKEY_NEXT = new AtomicInteger(123018);

    public int getSKU() { // Returns the int unique SKU number for this item
        //as you want increment of 2 so passing 2
        return PKEY_NEXT.addAndGet(2);
    }
}

【讨论】:

    【解决方案2】:

    定义以下类

    public static class SKU {
        private static int pkey_next = 123018;
    
        public static int getSKU() {
            return ++pkey_next;
        }
    }
    

    并使用以下语句获取方法

    SKU.getSKU()
    

    在你的情况下:

    System.out.println(SKU.getSKU());
    

    【讨论】:

      【解决方案3】:

      我猜这就是你被要求的:

      public class SKU { 
          private static int pkey_next = 123018;
          private int pkey;
      
          public SKU() {
              this.pkey = pkey_next++;
          }
      
          public int getSKU() { // Returns the int unique SKU number for this item
              return this.pkey;
          }
      }
      

      也就是说,实际给每个实例一个唯一的pkey值,使用静态字段作为计数器。

      SKU one = new SKU();
      SKU two = new SKU();
      SKU three = new SKU();
      System.out.println(three.getSKU()); // 123020
      

      【讨论】:

        【解决方案4】:

        您正在做一个后期增量,这就是为什么要获得相同的值。您需要在此处进行预增量,即在返回之前进行增量。 只需将return pkey_next++; 更改为++pkey_next;

        【讨论】:

          猜你喜欢
          • 2014-10-17
          • 1970-01-01
          • 2013-08-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-05
          • 1970-01-01
          相关资源
          最近更新 更多