comparing two collections for comparing two text files for additions, deletions, modifications

前端 未结 4 1020
鱼传尺愫
鱼传尺愫 2020-12-21 21:36

I have two collections as below which hold IDs for Students.

The ids are Strings in the format 111-1111. e.g. of ids 221-2534, 215-6365, etc.

 Collec         


        
4条回答
  •  情深已故
    2020-12-21 21:43

    Overall, I don't think this is the correct approach. Instead of storing all the information in a single String, I would create an object with fields for the various things you need to store.

    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
    
      }
    

    As for comparing the two collections, let's declare them both as ArrayLists and then keep track of the indices of what they have in common.

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

    You will need to tweak the above code a bit to make it fail-safe. Another approach is to use the contains method like this:

    for(int i=0; i

提交回复
热议问题