1、Parcelable实现对象的深度拷贝
深拷贝代码:
/**
* Parcelable深拷贝
* 注意:需要Parcelable才能进行深拷贝
*/
fun deepCopy(input: Parcelable): Parcelable? {
var parcel: Parcel? = null
return try {
parcel = Parcel.obtain()
parcel.writeParcelable(input, 0)
parcel.setDataPosition(0)
parcel.readParcelable(input.javaClass.classLoader)
} finally {
parcel?.recycle()
}
}
/**
* 数组Parcelable深拷贝
* 注意:需要Parcelable的数组才能进行深拷贝
*/
fun <T> deepCopyList(list: List<T>): List<T> {
try {
val result = mutableListOf<T>()
list.stream().forEach {
if (it is Parcelable) {
val aa = deepCopy(it)
result.add(aa as T)
}
}
return result
} catch (e: Exception) {
Log.e("TAG", "copyList异常$e")
}
return emptyList()
}
java代码深拷贝
//Serializable
public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
List<T> dest = (List<T>) in.readObject();
return dest;
}
// Parcelable
public static <T> List<T> deepCopyPar(List<T> src) throws IOException, ClassNotFoundException {
List<T> list=new ArrayList<T>();
for (int i = 0; i < src.size(); i++) {
Parcelable mParcelable= copy((Parcelable) src.get(i));
list.add((T) mParcelable);
}
return list;
}
public static Parcelable copy(Parcelable input) {
Parcel parcel = null;
try {
parcel = Parcel.obtain();
parcel.writeParcelable(input, 0);
parcel.setDataPosition(0);
return parcel.readParcelable(input.getClass().getClassLoader());
} finally {
if (null != parcel) {
parcel.recycle();
}
}
}
data数据
@Parcelize
data class User(val name: String, val age: String) : Parcelable
@Parcelize
data class User3(val name: String, val age: String, var list: List<User>) : Parcelable
生成数组:
val u3 = User3(
"父1", "45",
mutableListOf(User("张三", "13"), User("李四", "18"), User("王五", "25"))
)
val u31 = User3(
"父2", "46",
mutableListOf(User("张三", "13"), User("李四", "18"), User("王五", "25"))
)
val listUser = mutableListOf(u3, u31)
过滤数组
val copyList = deepCopyList(listUser)
val newList = copyList.stream().map {
var itemList = it.list.stream().filter { p ->
p.age == "18"
}.collect(Collectors.toList())
it.list = itemList
return@map it
}.collect(Collectors.toList())
Log.e("TAG", "过滤==>${newList}")
Log.e("TAG", "原数组==>$listUser")
最后运行输出的日志为:
2、序列化和反序列化来实现
思路:把数据对象转成json字符串,再把字符串转为数据对象
import com.google.gson.Gson
data class Person(val name: String, val age: Int)
fun main() {
val person = Person("Alice", 25)
// 序列化为JSON字符串
val gson = Gson()
val json = gson.toJson(person)
println(json) // 输出: {"name":"Alice","age":25}
// 反序列化为对象
val person2 = gson.fromJson(json, Person::class.java)
println(person2) // 输出: Person(name=Alice, age=25)
}
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
3、数组的深拷贝
A. data数组的深拷贝
data class Person(val name: String, val age: Int)
fun main() {
val originalArray = arrayOf(Person("Alice", 25), Person("Bob", 30))
val deepCopyArray = originalArray.map { it.copy() }.toTypedArray() //关键代码
// 修改原始数组的元素
originalArray[0] = Person("Charlie", 40)
println("Original Array:")
originalArray.forEach { println("Name: ${it.name}, Age: ${it.age}") }
println("Deep Copy Array:")
deepCopyArray.forEach { println("Name: ${it.name}, Age: ${it.age}") }
}
B.非data类型的数组
class Person {
var name: String? = null
var age: Int? = null
}
fun deepCopyPersonArray(persons: Array<Person>): Array<Person> {
return persons.map { person ->
Person().apply {
this.name = person.name
this.age = person.age
}
}.toTypedArray()
}
fun main() {
val originalPersons = arrayOf(
Person { name = "Alice"; age = 25 },
Person { name = "Bob"; age = 30 }
)
val copiedPersons = deepCopyPersonArray(originalPersons)
// 验证深拷贝是否成功
println(copiedPersons.contentEquals(originalPersons)) // 输出: true
println(copiedPersons[0] === originalPersons[0]) // 输出: false,表示两个对象不是同一个实例
}