深入剖析Java中String类的concat方法
作者:拘梦2014 时间:2023-06-02 07:07:13
Java String类的concat方法
在了解concat()之前,首先需要明确的是
String的两点特殊性
长度不可变
值不可变
这两点从源码中对String的声明可以体现:
private final char[] value ;
其中final对应值的不可更改的特性;而char[]对应String是长度不可更改的特性。
因此,当我们对String进行拼接后,产生的应该是一个新的字符串。
对于这一点,我们可以对concat()进行源码的解读得出同样的结论。
@param str
需要拼接到原字符串的新串@param otherlen
新串的长度@param len
原字符串的长度@param buf
存放最终字符串的字符数组(长度为len+otherlen)
@method copyOf(char[] original, int newLength)
复制指定的数组,截取或用 null 字符填充(如有必要),以使副本具有指定的长度。
@method getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
将字符从此字符串复制到目标字符数组。
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
源码分析
concat()方法首先获取拼接字符串的长度,判断这个字符串长度是否为0(判断这个用来拼接的字符串是不是空串),如果是就返回原来的字符串(等于没有拼接);否则就获取源字符串的长度,创建一个新的char[]字符数组,这个字符数组的长度是拼接字符串的长度与源字符串的长度之和,通过Arrays类的copyOf方法复制源数组,然后通过getChars方法将拼接字符串拼接到源字符串中,然后将新串返回。
API中也对这个方法进行了解释:
如果参数字符串的长度为 0,则返回此 String 对象。
否则,创建一个新的 String对象,用来表示由此 String 对象表示的字符序列和参数字符串表示的字符序列连接而成的字符序列。
综上,当对String对象进行拼接时,会创建一个新的字符串来存储新串。
String类中concat()方法笔记及底层实现
public String concat(String str)
将指定字符串连接到此字符串的结尾,需要创建对象才能够调用该方法,返回值为字符串。
public String concat1(String s){
String a = new String("jijeufh");
char [] b = new char[a.length()];
char [] d = new char[b.length+s.length()];
//创建一个能够容纳两个数组长度的数组
a.getChars(0,b.length,d,0);
//使用getChars方法,将对象数组中赋值到新的数组中,偏移量为0;
s.getChars(0, s.length(), d, b.length);
//使用getChars()方法将,参数数组赋值到新的数组中,偏移量对象数组的长度。
String dd = new String(d);
//通过String构造器将数组转换成为新的字符串。
return dd;
}
```
来源:https://blog.csdn.net/hebe_01/article/details/75043314
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android实现五子棋游戏(局域网版)
![](https://img.aspxhome.com/file/2023/0/126680_0s.jpg)
Java单例模式下的MongoDB数据库操作工具类
Java如何获取Date的“昨天”与“明天”示例代码
Spring注解之@Lazy注解使用解析
Java在制作jar包时引用第三方jar包的方法
![](https://img.aspxhome.com/file/2023/2/83042_0s.png)
Android Notification的多种用法总结
![](https://img.aspxhome.com/file/2023/3/129053_0s.jpg)
Android使用个推实现三方应用的推送功能
![](https://img.aspxhome.com/file/2023/4/138374_0s.png)
C# 调用 JavaWebservice服务遇到的问题汇总
Flutter实现手势识别功能详解方法
![](https://img.aspxhome.com/file/2023/5/116025_0s.gif)
公共POI导出Excel方法详解
![](https://img.aspxhome.com/file/2023/3/94213_0s.png)
轻松学习C#的异常处理
![](https://img.aspxhome.com/file/2023/9/100219_0s.jpg)
java web手写实现分页功能
![](https://img.aspxhome.com/file/2023/8/63028_0s.jpg)
Java源码解析之Iterable接口
kotlin之协程的理解与使用详解
![](https://img.aspxhome.com/file/2023/0/64420_0s.png)
springboot 自定义启动器的实现
![](https://img.aspxhome.com/file/2023/7/72567_0s.png)
Android编程使用AlarmManager设置闹钟的方法
Java中的Object类用法总结
![](https://img.aspxhome.com/file/2023/0/101910_0s.png)
Android刮刮卡效果实现代码
![](https://img.aspxhome.com/file/2023/2/138902_0s.gif)
Android开发技巧之像QQ一样输入文字和表情图像
![](https://img.aspxhome.com/file/2023/2/128982_0s.png)
Android-Service实现手机壁纸自动更换
![](https://img.aspxhome.com/file/2023/9/103899_0s.gif)