开发者

How do I copy an arraylist from one class to another in Java?

I understand that in orde开发者_StackOverflow社区r to copy an arraylist and have two lists independent of one another you must use a deep copy (copying the objects from one list to another not just the references), however is there a way this can be done cross-class?

For example; I am calling Class2 from Class1. In Class2 objects are added to an ArrayList of custom objects upon an event. I would like to be able to transfer this ArrayList to Class1 but whenever I try I get a NullPointer.

Any clues??


This is highly indicative of a design flaw.

See if you can't accomplish the same goal by wrapping your list in a class, sharing the class and using it to control access to the list.

The only case where this wouldn't just outright work is if your two classes must modify the list independently.

If this is a requirement, then I would probably hand a different instance of the wrapper class to each modifying class (with a reference to the same source list), then have a way for newly added data to be tagged with an ID referring to the original class--that way when you query, the wrapper would only return untagged items (items that were part of the original shared list) and items tagged with it's own ID.

Either that or the wrapper class could contain a second list and when queried, return the combined results of the original and second lists.

I've almost never wanted a deep copy. It happens, but it's quite rare.

If you post more info, maybe we can be more specific in helping with the redesign.

ALSO: (Edit) Chances are that the copied array list isn't your problem--it's probably that it wasn't TRULY a deep copy. For a deep copy, it means you implement a copy method (I believe they are supposed to be called .clone(), I never use this stuff--as I said, it's bad juju) for each object in the array list, then you call your copy method on each one to get the new copy in your next list.

Furthermore, any objects referenced by your copied object should probably be cloned as well. "Deep" means all the way down the tree.

I'm guessing you're failing somewhere in the process.

I'd really like to hear why you feel you need a copy instead of a reference.


My suggestion is for you to create a getArray() method and call it from the other class. This method should create a copy of the ArrayList because you should not "transfer" variables within classes; always with get() method so OO paradigm stays intact.

Do something like this:

Class 1

public ArrayList<Object> getArray() {
   ArrayList<Object> aux = new ArrayList<Object>();
    for(Object x : list) //object is the string, int, etc...
        aux.add(x.clone()) //assuming the Object has a clone method!
    return aux;
   }

On Class 2, just call this method. Then just look at the test from the other answer about the null exception, should work. Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜