System.arraycopy()方法详解
参考:https://blog.****.net/qq_32440951/article/details/78357325?utm_source=blogxgwz0
System中提供了一个native静态方法arraycopy(),可以使用这个方法来实现数组之间的复制
import java.util.Arrays;
import static java.lang.System.arraycopy;
public class Solution4 {
public static void main(String[] args) {
int[] arr1 ={1,2,3,4,5};
int[] arr2= {11,12,13,14,15};
arraycopy(arr1, 3, arr2, 2, 2);
System.out.println(Arrays.toString(arr2));
}
}
//[11, 12, 4, 5, 15]
关于次方法的示例代码1:
public class Solution3 {
private static String method(String s) {
// TODO Auto-generated method stub
if (s == null || s.length() == 0) {
return null;
}
int count = 0;
for (int i = 0; i < s.length(); i++) {//计算空格数目
if (s.charAt(i) == ' ') {
count++;
}
}
int oldLen = s.length();
//扩展数组的长度
int newLen = s.length() + 2 * count;
char[] newc = new char[newLen];
/**
* arraycopy(s.toCharArray(), 0, newc, 0, s.length())
*String.toCharArray 方法,作用:将字符串转换为字符数组。
*
*/
System.arraycopy(s.toCharArray(), 0, newc, 0, s.length());//index=0,相当于数组copy
//定义两个游标,i指向old组中的当前值,j指向newc数组中初始化的值,然后从后往前初始化newc数组,直到i指向0或者j追上i。
int i = oldLen - 1, j = newLen - 1;
while (i >= 0 && i < j) {
if (newc[i] == ' ') {
newc[j--] = '0';
newc[j--] = '2';
newc[j--] = '%';
} else {
newc[j--] = newc[i];
}
i--;
}
String newStr = new String(newc);//转换成字符串
return newStr;
}
public static void main(String[] args) {
String s = "1 2 3 4 5 6 7 8 9 0";
s = method(s);
System.out.println(s);
}
}
2
/*System中提供了一个native方法arraycopy()*/
public class SsytemArrayCopy {
public static void main(String[] args) {
User [] users=new User[]{new User(1,"admin","[email protected]"),new User(2,"maco","[email protected],com"),new User(3,"kitty","[email protected],com")};//初始化对象数组
User [] target=new User[users.length];//新建一个目标对象数组
System.arraycopy(users, 0, target, 0, users.length);//实现复制
System.out.println("源对象与目标对象的物理地址是否一样:"+(users[0] == target[0]?"浅复制":"深复制"));
target[0].setEmail("[email protected]");
System.out.println("修改目标对象的属性值后源对象users:");
for (User user : users){//User user 相当于User user=new User();会调用构造函数User{}的方法
System.out.println(user);
}
}
}
class User{
private Integer id;//实例变量
private String username;
private String email;
//无参构造函数
public User() { }
//有参的构造函数
public User(Integer id, String username, String email) {
super();//调用父类的构造函数
this.id = id;//注意this()与this的区别,
this.username = username;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {//此处才为方法
return "User [id=" + id + ", username=" + username + ", email=" + email
+ "]";
}
}