字符串拼接时数值类型相加引发的问题

背景

多个字段再进行,字符串拼接的过程中,需要格外留意待拼接的字段的类型,如果是数值类型的话,则需要小心出现bug。

如:String str = item.getSkuId() + item.getSkuType() + item.getClassicId() + item.getCurrency() + item.getStartTime() ;

各个字段的值分别是:101、1、1101、CNY、1687624332000

你期望的输出是:10111101CNY1687624332000

但实际的输出确是:1203CNY1687624332000

代码

public class ClassicPriceSettingReqDto {

    private Integer skuId;

    private Byte skuType;

    private Long classicId;

    private String currency;

    private Long startTime;

    public Integer getSkuId() {
        return skuId;
    }

    public Byte getSkuType() {
        return skuType;
    }

    public Long getClassicId() {
        return classicId;
    }

    public String getCurrency() {
        return currency;
    }

    public Long getStartTime() {
        return startTime;
    }
}

出错的写法

Set<String> existsDataSet = new HashSet<>();
for (ClassicPriceSettingReqDto item : reqDtoList) {
    // 按照指定字段进行去重,前三个字段均为数值类型,而我想要的是字符串的拼接效果
    String str = item.getSkuId() + item.getSkuType() + item.getClassicId() + item.getCurrency() + item.getStartTime() ;
    if (existsDataSet.contains(str)) {
        log.warn("This data already exists {}", str);
        continue;
    }
    existsDataSet.add(str);
    
}

正确的写法

Set<String> existsDataSet = new HashSet<>();
for (ClassicPriceSettingReqDto item : reqDtoList) {
    // 按照指定字段进行去重
    String str = item.getSkuId() + "-" + item.getSkuType() + "-" + item.getClassicId() + "-" + item.getCurrency() + "-" + item.getStartTime() ;
    if (existsDataSet.contains(str)) {
        log.warn("This data already exists {}", str);
        continue;
    }
    existsDataSet.add(str);
    
}

本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

首发链接:https://www.cnblogs.com/lingyejun/p/17501927.html

猜你喜欢

转载自blog.csdn.net/lingyejun/article/details/131369591