android——深拷贝、过滤

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,表示两个对象不是同一个实例
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wy313622821

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值