栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

比较两个集合,比较两个文本文件的添加,删除和修改

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

比较两个集合,比较两个文本文件的添加,删除和修改

总体而言,我认为这不是正确的方法。与其将所有信息存储在单个String中,不如创建一个对象,其中包含用于存储您需要存储的各种内容的字段。

public Student {   String id; //or int, or char[8]   String firstName, lastName;   String address;  //and so on  //constructor - Given a line of input from the data file, create a Student object  public Student(String line) {     id = line.substring(0,8);     //and so on  }

至于比较这两个集合,让我们将它们都声明为ArrayLists,然后跟踪它们共同点的索引。

ArrayList<String> newKeys = new ArrayList<>();  //java 7 syntaxArrayList<String> oldKeys = new ArrayList<>();//store keys from files.TreeMap<Integer, Integer> commonKeys = new TreeMap<Integer, Integer>();//stores the index values from newList as keys that get mapped to the old list index.ArrayList<Integer> removedKeys =ArrayList<>();  // Store the indices from oldKeys that are not in newKeys.int newListIndex = 0;int oldListIndex = 0;while(newListIndex < newKeys.size() && oldListIndex<oldKeys.size()) {   if(newKeys.get(newListIndex).equals(oldKeys.get(oldListIndex) ) {      commonKeys.put(newListIndex,oldListIndex);      oldListIndex++; newListIndex++    }   else if(newKeys.get(newListIndex).compareTo(oldKeys.get(oldListIndex)>0 ) {      removedKeys.add(oldListIndex);      oldListIndex++   }   else {      //maybe this is a newListIndex that is not in the old list, so it was added.      newListIndex++;   }}

您将需要稍微调整上面的代码以使其失效保护。另一种方法是使用包含方法,如下所示:

for(int i=0; i<oldKeys.size(); i++) {   String oldKey = oldKeys.get(i);   if(newKeys.contians(oldKey);       commonKeys.put(newKeys.indexOf(oldKey) , i);   else       removedKeys.add(i);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508064.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号