开发者

Cloning a List - how is it done?

开发者 https://www.devze.com 2023-03-04 23:29 出处:网络
I want to make a shallow copy of a List I get returned by a method call (it\'s public List getScanResults () from Android, see http://developer.android.com/reference/android/net/wifi/WifiManager.html#

I want to make a shallow copy of a List I get returned by a method call (it's public List getScanResults () from Android, see http://developer.android.com/reference/android/net/wifi/WifiManager.html#getScanResults%28%29). The problem is, clone() is not defined on the List interface, but only on concrete classes like ArrayList - however I don't know what getScanResults() uses internally, so I can't just simply cast it or am I wrong about this? I then thought of something like

开发者_如何学JAVA

anExistingList.add(getScanResults());

but getScanResults() seems to return null instead of an empty list if there's nothing to return, so that is also no option. When I would do something like

if(getScanResults() != null)
    anExistingList.add(getScanResults());

the return value of getScanResults() could change between the first code line and the second one, therefore it could pass the "not equals null" condition first and then be null in the second line or am I wrong about this?

So, how would I make a shallow copy of the return value of getScanResults() or just formulating my goal: Getting a value from getScanResults() and make sure it doesn't change while I am working with it?

Thanks for any hint :-) (I guess I am just understanding something wrong)


Look here. java.util.Collections provides the static method copy to copy the contents from one list to another.


All well behaved collections have copy constructors. So create an instance of the type of list you want, depending on your needs (e.g. fast indexing or efficient removal of some elements).

In this case, you have to do a little bit more to handle the inconvenience of a possible null. So something like this:

/**
 * @return a copy of the original; an empty list if original is null.
 */
public static <T> List<T> randomAccessibleCopy(List<T> original) {
    return (null == original) 
             ? Collections.<T>emptyList() 
             : new ArrayList<T>(original);
}

Now you can call this method with the results of the underlying API that returns the list.


if(getScanResults() != null)
    anExistingList.add(getScanResults());

should be

List x = getScanResults();
if(x != null)
    anExistingList.add(x);

As the method now is called only once, it can't change in the meantime.

0

精彩评论

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