JDK-4187872 : Can't implement Map and List in the same class because of remove(Object) method
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 1.2.0
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: generic
  • CPU: generic
  • Submitted: 1998-11-06
  • Updated: 2021-03-03
  • Resolved: 1998-11-06
Description

Name: tb29552			Date: 11/06/98


I have a need for a collection that maintains an
ordered list (like ArrayList) but allows fast
access by a key (like HashMap).  My particular
use for this is withing a TableModel that
represents database rows that may be changed by
other objects.  I would like to implement both the
List and Map interfaces.  It appears that the one
and only barrier to this is that both interfaces
contain a remove(Object) method, but they return
different things.  List returns boolean, while Map
returns Object.

You can't create a set of methods that will
compile for the following class declaration:

import java.util.*;
public class HashList
    implements List, Map
{
}

I know it's late in the release cycle to do this,
but if it's not done now -- when?

I'd like List to return the object removed, with
null for a failure to find it.
(Review ID: 42265)
======================================================================

Comments
WORK AROUND tim.bell@Eng 2000-06-29 The source code (LinkedHashMap.java) mentioned in the Evaluation is available as part of the J2SDK 1.3 beta SCSL source bundle, which can be obtained from: http://www.sun.com/software/java2/download.html After you agree to the SCSL license and download the source bundle, look for: ext/jpda/src/share/classes/com/sun/tools/jdi/LinkedHashMap.java
11-06-2004

PUBLIC COMMENTS .
10-06-2004

EVALUATION This should probably be an FAQ. It is intentional that a class cannot implement List and Map simultaneously. Even if it were possible from a method signature point-of-view, it would be impossible semantically. In particular, the equals contracts implies that it's not possible for a Map to be equal to a List, or vice versa. Similarly, the hashCode contracts would mandate two different HashCode computations. It is possible to get a very similar effect by having an object that implements Map and provides a List-view operation ("asList()"), or vice-versa. Also, it's possible to implement a Map that guarantees insertion-order iteration but does not implement the List interface. I've attached source code for such a class to this bug report. Customers can use this code freely (as-is). joshua.bloch@Eng 1998-11-06
06-11-1998