Java函数如何实现数据拷贝和类型转换的功能?
发布时间:2023-06-07 08:00:05
Java中提供了一个Arrays类和一个System类,它们都提供了一些方法来实现数据拷贝和类型转换的功能。
## 数据拷贝
### Arrays类
Arrays类中的copyOf()方法可以将一个数组中的指定元素拷贝到一个新的数组中。
// 语法
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
// 示例
String[] strs1 = {"Java", "Python", "C++"};
String[] strs2 = Arrays.copyOf(strs1, 3); // 拷贝整个数组
String[] strs3 = Arrays.copyOf(strs1, 2); // 拷贝前两个元素
String[] strs4 = Arrays.copyOf(strs1, 5); // 拷贝前三个元素,并将新数组扩展到5个元素
### System类
System类中的arraycopy()方法可以将一个数组中的元素拷贝到另一个数组中。
// 语法
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
// 示例
int[] nums1 = {1, 2, 3};
int[] nums2 = new int[3];
System.arraycopy(nums1, 0, nums2, 0, 3);
## 类型转换
### Arrays类
Arrays类中的asList()方法可以将一个数组转换成一个List集合。
// 语法
public static <T> List<T> asList(T... a)
// 示例
String[] strs = {"Java", "Python", "C++"};
List<String> list = Arrays.asList(strs); // 将数组转换成List集合
### System类
System类中的identityHashCode()方法可以获取一个对象的哈希码。
// 语法 public static int identityHashCode(Object x) // 示例 String str = "Java"; int hashCode = System.identityHashCode(str); // 获取字符串的哈希码
