fuin.org

Small Open Source Java Tools and Libraries

Tracking changes of a list

This is a wrapper for lists that keeps track of all changes made to the list. This means adding, replacing or deleting elements is tracked - not the changes to the objects itself. It's also possible to revert (undo) all changes made to the list. A restriction is that no duplicate elements are allowed in the list.
        
        // Create a standard string list
        List list = new ArrayList();
        
        // Add some initial content
        list.add("one");
        list.add("two");
        list.add("three");
        
        // Wrap the list to track changes
        final ChangeTrackingUniqueList trackingList = new ChangeTrackingUniqueList(list);
        
        // Add and remove some items
        trackingList.add("four");
        trackingList.add("five");
        trackingList.remove("three");
        
        // Print the status
        // Output: true
        System.out.println("HAS CHANGED:");
        System.out.println(trackingList.isChanged());
        System.out.println();
        
        // Print the deleted items
        // Output: "three"
        System.out.println("DELETED:");
        printList(trackingList.getDeleted());
        
        // Print the added items
        // Output: "four", "five"
        System.out.println("ADDED:");
        printList(trackingList.getAdded());
        
        // Revert all changes        
        trackingList.revert();
        
        System.out.println("REVERTED:");
        // Output: "one", "two", "three"
        printList(trackingList);        
        
You can find a full example here Internal link outside layout (Package "org.fuin.examples.utils4j").