我在Java中有两个哈希集,我希望找到差异
我按照Oracle的文档
的推荐尝试了以下代码 HashSet<RunningTaskInfo> difference = new HashSet<ActivityManager.RunningTaskInfo>(newRunningTasks);
HashSet<RunningTaskInfo> oldRunningTaskInfos = new HashSet<ActivityManager.RunningTaskInfo>(oldRunningTasks);
difference.removeAll(oldRunningTaskInfos);
for(RunningTaskInfo d : difference){
ComponentName cn = d.baseActivity;
Log.d("com.manugupt1.fua","Comparing : " + i + cn.getPackageName() + "****" + cn.getClassName() + "****" + cn.getShortClassName());
}
只应显示那些不在oldRunningTasks中的数据值,但我只获取oldRunningTasks中的元素。任何建议
答案 0 :(得分:2)
编辑:添加马特的评论
RemoveAll正在比较对象指针而不是内容,这就是为什么它无法找到任何巧合。
您可以通过观看
的返回值来查看此内容difference.removeAll(oldRunningTaskInfos);
(错误意味着“没有巧合”)
可能最好的方法是将RunningTask封装到一个覆盖equals()和hashcode()方法的对象中,然后调用removeAll。请考虑以下示例代码,这些代码执行相同操作,但使用List:
// Getting two snapshots
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> oldRunningTasks=am.getRunningTasks (100);
List<ActivityManager.RunningTaskInfo> newRunningTasks=am.getRunningTasks (100);
// We add a new fake task to test that removeAll() is working
ActivityManager.RunningTaskInfo fakeTask=new ActivityManager.RunningTaskInfo ();
fakeTask.baseActivity=new ComponentName("Fake","Fake");
fakeTask.id=1234;
newRunningTasks.add(fakeTask);
// Converting to lists of Comparable objects and get the differences.
List<RunningTaskInfoComparable> list_difference = convertToComparable(newRunningTasks);
List<RunningTaskInfoComparable> list_oldRunningTaskInfos = convertToComparable(oldRunningTasks);
boolean res=list_difference.removeAll(list_oldRunningTaskInfos);
for(RunningTaskInfoComparable d : list_difference){
ComponentName cn = d.getBaseActivity();
Log.d("com.test.tasks","Comparing List: " + cn.getPackageName() + "****" + cn.getClassName() + "****" + cn.getShortClassName());
}
其中RunningTaskInfoComparable的实现如下:
public class RunningTaskInfoComparable {
android.app.ActivityManager.RunningTaskInfo runningTaskObject;
public RunningTaskInfoComparable (android.app.ActivityManager.RunningTaskInfo obj)
{
runningTaskObject=obj;
}
// Observer
public ComponentName getBaseActivity(){
return runningTaskObject.baseActivity;
}
@Override
public int hashcode()
{
int result = HashCodeUtil.SEED;
// More data could be added to the hash...
result = HashCodeUtil.hash( result, runningTaskObject.id);
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RunningTaskInfoComparable)) {
return false;
}
// Criteria: Same task id means same entity
return (runningTaskObject.id==((RunningTaskInfoComparable)obj).runningTaskObject.id);
}
}
和convertToComparable看起来像:
private List<RunningTaskInfoComparable> convertToComparable (List<ActivityManager.RunningTaskInfo> _original)
{
List<RunningTaskInfoComparable> retList=new ArrayList<RunningTaskInfoComparable>();
for(RunningTaskInfo t : _original){
RunningTaskInfoComparable tc = new RunningTaskInfoComparable(t);
retList.add(tc);
}
return retList;
}