Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6125007
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T16:11:54+00:00 2026-05-23T16:11:54+00:00

The Java Collections interfaces (for example, List or Set ) define the contains method

  • 0

The Java Collections interfaces (for example, List or Set) define the contains method to accept any Object.

 public boolean contains(Object o)

However, when it comes to implementing this method, the particular collection I’m working on requires that I have a type which is compatible with the generic type E of the class (i.e. either be class E, or a subclass of E, or a class which implements E if E is an interface). In other words, if o is castable to type E, then it is compatible. This presents an issue because Java erases the Generic type information, so something like this isn’t possible:

public boolean contains(Object o)
{
    if(o instanceof E) // compile error due to type erasures
    {
        // ... check if this collection contains o
    }
    return false;
}

My question is what would be the best way to accomplish something like this? The Oracle Article on Type Erasures mentions that this forbidden, but does not offer any solutions to this problem.

I can only think of one semi-elegant way to get around this:

Make a cast to type E. If the cast fails, o cannot be type E or a subclass of type E.

public boolean contains(Object o)
{
    try
    {
        E key = (E) o; // I know it's unsafe, but if o is castable to E then the method should work
        // check if this collection contains key
    }
    catch(ClassCastException e)
    {
        // invalid type, cannot contain o
    }
    return false;
}

While this would work, it looks messy (I’m not a big fan of using Exceptions in this manner).

Is there a better way to accomplish this same goal (changing the method signature is not allowed)?

edit: yeah, this doesn’t work because E gets erased to Object 🙁

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T16:11:54+00:00Added an answer on May 23, 2026 at 4:11 pm

    This is only possible by (1) passing in the expected Class, or (2) examining the generic type parameters of some reflective element that defines <E>. Let me elaborate.

    The most common case is to simply require the caller to pass in the runtime class of E.

    public class MyClass<E> {
        private final Class<E> realType;
        public MyClass(Class<E> realType) {
            this.realType = realType;
        }
        public boolean Contains(Object o) {
            E e = realType.cast(o); // runtime cast - will throw ClassCastException.
            // Could also use realType.isInstance(o)
            // or realType.isAssignableFrom(o.getClass())
            ...
        }
    }
    

    Caller:

    new MyClass<MyObject>(MyObject.class)
    

    This is generally type safe since the compiler will verify that the <E>‘s match. Of course the caller can bypass the compiler’s checks…nothing you can do about that!

    For (2), what I mean is that you can use reflection to examine static generic type parameters. This probably isn’t a good option in your case because you must have access to some field, method, or superclass declaration that statically defines <E>. The most common way is to make your class abstract and have callers extend it. This approach is used by Hamcrest’s TypeSafeMatcher (see ReflectiveTypeFinder) to great effect. (Note that TypeSafeMatcher is basically just making option (1) easier for the programmer; it still provides a constructor that takes the Class for cases when reflection doesn’t work!) If you want to get really fancy, you can inspect getClass().getGenericSuperclass().getActualTypeArguments(). This isn’t as easy as it sounds — see this good article. I’m not even sure that article covers all the edge cases — you’re basically reimplementing the compiler! So just go with option (1) and be happy you’re not using generics in C# 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

import java.util.Collection; import example.Event; public interface Query { public boolean hasMore (); public Collection<Event>
In the Java collections framework, the Collection interface declares the following method: <T> T[]
Java collections only store Objects, not primitive types; however we can store the wrapper
The Java Collections.max method takes only a collection of a sortable ( Comparable )
Do Java collections have a built-in method to return multiple items from that collection?
I am familiar with Java Collection Framework which contains basic interfaces: Collection and Map
The API for the Java Set interface states: For example, some implementations prohibit null
I just learned about how the Java Collections Framework implements data structures in linked
I wanted to make Map of Collections in Java, so I can make something
While creating classes in Java I often find myself creating instance-level collections that I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.