Question

I am reading Core Java Volume I - fundamentals (9th edition) by Cay S. Horstmann and Gary Cornell. Here is a paragraph from the book which I do not understand. If you could demonstrate with a simple example what it means, it would be great. Thanks

List<String> staff = new LinkedList<>();
.....
lookAt(Collections.unmodifableList(staff));
.....
.....
.....

paragraph : The undmodifiableCollection methods returns a collection whose equal method does not invoke the equals method of the underlying collection. Instead it inherits the equals method of the object class, which just tests whether the objects are identical. If you turn a set or list into just collection, you can no longer test for equal contents. The view acts in this way because equality testing is not well-defined at this level of hierarchy. The view treats the hash code method in the same way. However, the unmodifiableSet and unmodifiableList methods use the equals and hashCode methods of the underlying collections.

Was it helpful?

Solution

Normally two lists that are not the same list but that have the same contents are considered equal. Two unmodifiable lists that have the same contents are similarly equal.

Two unmodifiable collections on the other hand, are not equal just because they have the same contents.

        List<Integer> list1 = new ArrayList<Integer>();
        list1.add(Integer.valueOf(1));
        list1.add(Integer.valueOf(2));
        List<Integer> list2 = new LinkedList<Integer>();
        list2.add(Integer.valueOf(1));
        list2.add(Integer.valueOf(2));
//True!
        System.out.println(list1.equals(list2));

        List<Integer> unModList1 = Collections.unmodifiableList(list1);
        List<Integer> unModList2 = Collections.unmodifiableList(list2);
//True!
        System.out.println(unModList1.equals(unModList2));

        Collection<Integer> unModColl1 = Collections.unmodifiableCollection(list1);
        Collection<Integer> unModColl2 = Collections.unmodifiableCollection(list2);
//False
        System.out.println(unModColl1.equals(unModColl2));

OTHER TIPS

List<String> list1 = new ArrayList<String>();
list1.add("foo");
List<String> list2 = new ArrayList<String>();
list2.add("foo");

System.out.println("Are lists equal: " + list1.equlas(list2));
System.out.println("Are unmod collections equal: " + 
  Collections.unmodifiableCollection(list1).equals(
  Collections.unmodifiableCollection(list2)));
System.out.println("Are unmod lists equal: " + 
  Collections.unmodifiableList(list1).equals(
  Collections.unmodifiableList(list2)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top