2

I'm trying to copy elements from one arrayList into another, I starting getting errors in my app and I think the problem is that I was doing shallow copies.

How can I add an item from one array into another doing a deep copy/clone?

This is how I was copying the elements up to now:

public ArrayList<ResolveInfo> myAppsArr = new ArrayList(); 
public ArrayList<ResolveInfo> allAppsArr = new ArrayList(); 

    myAppsArr.add(allAppsArr.get(0));
3
  • Yeah, that just copies references. Commented Jan 13, 2013 at 20:12
  • 1
    Are you nor sure? 'I think the problem is that I was doing shallow copies'. You should be sure before starting to make deep copies. Commented Jan 13, 2013 at 20:14
  • You should use copy constructor of the ResolveInfo class Commented Jan 13, 2013 at 20:17

2 Answers 2

3

How can I add an item from one array into another doing a deep copy/clone?

ResolveInfo has a constructor that creates new duplicate object for you:

myAppsArr.add(new ResolveInfo(allAppsArr.get(0)));

It appears this constructor was only added in API 17, you can try the generic clone method:

myAppsArr.add(allAppsArr.get(0).clone()); // No promises, I haven't tested this myself

Or you can create a method that manually creates a new ResolveInfo object since all of the member data is public.

Sign up to request clarification or add additional context in comments.

Comments

2

The easiest and most reliable way to do this for all android versions is to serialize ResolveInfo to parcel and create new ResolveInfo instance from that parcel.

ResolveInfo r1 = new ResolveInfo();
Parcel p = Parcel.obtain();
r1.writeToParcel(p, 0);
ResolveInfo r2 = ResolveInfo.CREATOR.createFromParcel(p);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.