gpt4 book ai didi

java - 传递可解析/可序列化与传递对象的数据成员

转载 作者:太空宇宙 更新时间:2023-11-04 14:34:12 25 4
gpt4 key购买 nike

我试图找出在android中将对象从一个 Activity 传递到另一个 Activity 的最有效方法是什么。我读到我可以将对象扩展为 Parcelable 或 Serialized,而且就性能而言,Parcelable 似乎是明显的赢家。

现在我想到了一个不同的方法。我不会扩展任何类,而是将所有数据变量放入一个包中,传递这些数据,然后重建对象。例如:

public class myObject {
// Data Variables
private String str1;
private String str2;
private boolean bool1;

// Constructor
public myObject(String str1, String str2, boolean bool1){
this.str1 = str1;
this.str2 = str2;
this.bool1 = bool1;
}
}

现在我将传递变量:

Intent i = new Intent();
i.setClass(ActOne.this, ActTwo.class);
Bundle bundle = new Bundle();
bundle.putString("KEY_STR1", str1);
bundle.putString("KEY_STR2", str2);
bundle.putBoolean("KEY_BOOL1", bool1);
startActivity(i);

在 ActTwo 类中,我将从 Intent 中获取数据并重建我的对象:

myObject newObjHolder = new myObject(str1, str2, bool1);

这种方式与传递 Parcelable 相比如何?快点?慢点?几乎没有什么区别?

最佳答案

如果您仔细观察,您会发现 Bundle 无论如何都只是一个 Parcelable。因此,您可能正在研究一些非常小、效率较低的方法来实现您建议的方式。

我来告诉你原因:Parcelables 必须在 Parcel 中写入,而您在 Bundle 中写入,则该 Bundle 会将其写入 Parcel。因此,您确实增加了一些开销,但您可能可以进行类似于@bhowden 指向的链接的测试,并看到它会非常小。

那么你必须决定你是喜欢 Bundle 的简单代码还是 Parcelable 的速度。

关于java - 传递可解析/可序列化与传递对象的数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25792722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com