首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >字符串拼接时数值类型相加引发的问题

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

作者头像
翎野君
发布2023-07-01 14:43:14
发布2023-07-01 14:43:14
3530
举报
文章被收录于专栏:翎野君翎野君

背景

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

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

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

你期望的输出是:10111101CNY1687624332000

但实际的输出确是:1203CNY1687624332000

代码

代码语言:javascript
复制
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;
    }
}

出错的写法

代码语言:javascript
复制
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);
    
}

正确的写法

代码语言:javascript
复制
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);
    
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-06-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
  • 代码
    • 出错的写法
    • 正确的写法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档