0

I want to put an ArrayList<HashMap<String, Object>> into another ArrayList<HashMap<String, Object>>. How can I do that?

I was trying with the assignment operator (=) but I found out that it just points to the reference, I want to put the elements into another.

1
  • So you want to copy everything, including he objects within the HashMap, correct? Commented Jun 21, 2012 at 20:11

3 Answers 3

4

You can use the addAll method, but bear in mind that'll not duplicate the HashMaps and much less the Objects within!

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

Comments

1

Try this:

List<HashMap<String, Object>> newList = new ArrayList<HashMap<String,Object>>();
for (HashMap<String, Object> hm: oldList) {
    newList.add(hm);
}

2 Comments

I didn't make any point about addAll. My method is pretty quick and dirty, but for a real eye-opener, look at the source of addAll() in ArrayList.java.
He he, sorry, you did not make a point indeed. I guess I was making it, that addAll would be more compact and do the same
1

You can create a new ArrayList Object and just call the addAll method and pass the ArrayList you want to copy

Another way is Collections.copy(desc,src) but this is not feasible since the size of both the List must be equal.

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.