代码之家  ›  专栏  ›  技术社区  ›  wutzebaer

如何在调用另一个构造函数之前拆分字符串

  •  2
  • wutzebaer  · 技术社区  · 6 年前

        public final long x;
        public final long y;
        public final int level;
        private final int hash;
        public final Point tileCenter;
    
        public TileCoordinate(long x, long y, int level) {
            this.x = x;
            this.y = y;
            this.level = level;
            this.hash = Objects.hash(x, y, level);
            this.tileCenter = getTileCenter();
        }
    
        public TileCoordinate(String key) {
            String[] bits = key.split("-");
    //      this.level = Integer.parseInt(bits[0]);
    //      this.x = Long.parseLong(bits[1]);
    //      this.y = Long.parseLong(bits[2]);
            this(Long.parseInt(bits[0]),Long.parseLong(bits[1]),Integer.parseLong(bits[2]));
            this.hash = Objects.hash(x, y, level);
            this.tileCenter = getTileCenter();
        }
    

    因为我不想写 this(Integer.parseInt(key.split("-")[0]),Long.parseLong(key.split("-")[1]),Long.parseLong(key.split("-"))); ,我的选择是什么?

    3 回复  |  直到 6 年前
        1
  •  4
  •   rgettman    6 年前

    String[] bits = key.split("-"); 避免在延迟构造函数调用中调用它3次 this() ,如果它存在,则必须是构造函数中的第一条语句。

    将实际字段赋值委托给构造函数,而不是委托给构造函数 private 方法来处理字段分配。

    public TileCoordinate(String key) {
        String[] bits = key.split("-");
        init(Long.parseInt(bits[0]),Long.parseLong(bits[1]),Integer.parseInt(bits[2]));
        this.hash = Objects.hash(x, y, level);
        this.tileCenter = getTileCenter();
    }
    
    private void init(long x, long y, int level) {
        // assign to fields here
    }
    

    私有的 所以它不能被覆盖,如果泄漏 this

    您可能还想验证一下 bits 在继续之前有3个元素。

        2
  •  3
  •   Karol Dowbecki    6 年前

    呼吁 this() super() Factory Method :

    public static TileCoordinate parseTitleCoordinate(String key) {
      String[] bits = key.split("-");
      long x = Long.parseLong(bits[0]);
      long y = Long.parseLong(bits[1]);
      long level = Long.parseLong(bits[2]);
      return new TitleCoordinate(x, y, level);
    }
    

    final

        3
  •  0
  •   Zack    6 年前

    无法重载初始化方法:

      public TileCoordinate(long x, long y, int level) {
          init(x, y, level);
      }
    
      public TileCoordinate(String key) {
          init(key);
      }
    
      private void init(String key) { 
          String[] bits = key.split("-");
          init(Long.parseLong(bits[0]),
               Long.parseLong(bits[1]),
               Integer.parseInt(bits[2]));
      }
    
      private void init(long x, long y, int level) { 
          this.setX(x);
          this.setY(y);
          this.setLevel(level);
      }
    

    这保持了单一责任。只有第二个init方法正在调用setter,其余方法正在委派。