【问题标题】:How can i use toString method in a optimum way with StringBuilder我如何以最佳方式使用 toString 方法与 StringBuilder
【发布时间】:2020-06-25 16:46:53
【问题描述】:

我怎样才能改变这种方法变得更 通过使用优化 字符串生成器 并避免每次都与 + 进行字符串连接。

或者可能有更好的方法

public class Cont {
    double valoareImprumut;
    double rata;
    int zileActive;
    TipCont tipCont; //ENUM

    @Override
    public String toString() {
        return "Cont [valoareImprumut=" + valoareImprumut + ", rata=" + rata + ", zileActive=" +zileActive + ", tipCont=" + tipCont + "]";
    }

【问题讨论】:

  • 如果使用 Java 8,编译器会将该代码转换为使用 StringBuilder。如果使用 Java 9+,它会将代码转换为使用StringConcatFactory。也就是说,你可以继续使用+
  • 好的,知道了。出于好奇,只想比较带有 + 连接的 toString 与不带 + 的 StringBuilder。但我不知道怎么做。

标签: java string object tostring


【解决方案1】:

您可以使用 Lombok 并完全避免编写 toString() 方法:)

https://projectlombok.org/features/ToString

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2023-04-08
    • 2010-12-15
    相关资源
    最近更新 更多