【发布时间】:2009-12-07 03:46:57
【问题描述】:
假设我有一个列表 A,它需要看起来与列表 B 完全相同。B 拥有但 A 没有的所有对象都需要添加到 A。A 拥有但 B 没有的所有对象都需要添加从 A 中删除。
我需要这个的原因是因为我有一个播放器的 ArrayList,我要保存到一个文件中。每次更新 Player 的属性时,我都会通过调用查看 Player 的 ArrayList 并保存它的方法来保存对文件的更改。这是可行的,因为 ArrayList 具有对 Players 的引用。
但是,每当我在列表中搜索播放器时,我首先会通过读取其存储位置的文件来更新列表。这会将所有引用替换为全新的对象。在我这样做之后,如果我对以前获取的用户进行更改并尝试保存它。 Player 的新实例被保存,而不是我在其中进行更改的那个。
会想出一个好的算法来使一个列表等于另一个解决方案吗?或者有没有更好的方法来更新整个列表,同时保留在那里使用的引用?
更新:更新的解决方案,在 O(nlogm) 时间内运行。遍历目标中的每个元素,在源中搜索它。如果找到,请从源中删除。如果不是,则从目的地中删除。然后将源中的剩余元素添加到目标。列表当然需要排序,但我从文件中获取的列表已经排序,因为我在添加时排序。
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CopyList {
public static void copyList(List dest, List src) {
copy(dest, src);
// the remaining elements in src list will be those that were originally
// in src but not in dest and so they need to be added
dest.addAll(src);
}
public static void copyList(List dest, List src, Verify v) {
copy(dest, src);
// the remaining elements in src list will be those that were originally
// in src but not in dest and so they need to be added
addAll(dest, src, v);
}
public static void copyList(List dest, List src, Comparator c) {
copy(dest, src, c);
// the remaining elements in src list will be those that were originally
// in src but not in dest and so they need to be added
dest.addAll(src);
}
public static void copyList(List dest, List src, Comparator c, Verify v) {
copy(dest, src, c);
// the remaining elements in src list will be those that were originally
// in src but not in dest and so they need to be added
addAll(dest, src, v);
}
private static void copy(List dest, List src) {
// go through dest list to search if every element is in the new list
// travel backwards through dest because we will be removing elements from it
for(int i = dest.size()-1; i >= 0 ; i--) {
int src_i = Collections.binarySearch(src, dest.get(i));
if(src_i >= 0)
// if element is found in src list, remove it from src list
src.remove(src_i);
else
// if element is NOT found in src list, remove it from dest list
dest.remove(i);
}
}
private static void copy(List dest, List src, Comparator c) {
// go through dest list to search if every element is in the new list
// travel backwards through dest because elements might be removed
for(int i = dest.size()-1; i >= 0 ; i--) {
int src_i = Collections.binarySearch(src, dest.get(i), c);
if(src_i >= 0)
// if element is found in src list, remove it from src list
src.remove(src_i);
else
// if element is NOT found in src list, remove it from dest list
dest.remove(i);
}
}
private static void addAll(List dest, List src, Verify v) {
// verify each element in src list before adding it to dest list
for(Object o: src)
if(v.verify(o))
dest.add(o);
}
}
【问题讨论】:
标签: java algorithm search reference arraylist