我有一个 mArraylist 对象,在 mArraylist add(object) 之后发生了奇怪的事情; 这是我的来源。为什么 aj1 等于 arraylist 中的 aj2。这让我发疯!怎么了?
/*get a mArraylist*/
ArrayList<JSONObject> ajson;
/*get an object that to be add.*/
JSONObject jsonObject = new JSONObject();
/*check result*/
ArrayList<JSONObject> aj1 = new ArrayList<JSONObject>();
aj1 = ajson;
int size_outter = ajson.size();
ArrayList<JSONObject> aj2 = new ArrayList<JSONObject>();
ajson.add(jsonObject);
aj2 = ajson;
int size_inner = ajson.size();
/*check aj1,aj2,eqauls*/
if (aj1.equals(aj2))
{
System.out.println("aj1.equals(aj2)======true==");
}
System.out.println("aj1=ajson============size" + size_outter);
System.out.println("aj2=ajson============size" + size_inner);
System.out.println("aj1=============size" + aj1.size());
System.out.println("aj2=============size" + aj2.size());
//the output is
11-26 12:40:37.885: INFO/System.out(7214): aj1.equals(aj2)======true==
11-26 12:40:37.885: INFO/System.out(7214): aj1=ajson============size0
11-26 12:40:37.885: INFO/System.out(7214): aj2=ajson============size1
11-26 12:40:37.885: INFO/System.out(7214): aj1=============size1
11-26 12:40:37.885: INFO/System.out(7214): aj2=============size1
why aj1 equals aj2? but its size is not?
最佳答案
aj1 和 aj2 是对同一对象 (ajson) 的 2 个引用,您在这两行时这样做了:
aj1 = ajson;
...
aj2 = ajson;
事实上大小是一样的:
11-26 12:40:37.885: INFO/System.out(7214): aj1=============size1
11-26 12:40:37.885: INFO/System.out(7214): aj2=============size1
这一行:
if (aj1.equals(aj2))
你在比较同一个对象。
关于android - ArrayList 中的奇怪事物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8276445/