总体而言,我认为这不是正确的方法。与其将所有信息存储在单个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);}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)