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 764049
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T16:39:34+00:00 2026-05-14T16:39:34+00:00

I have come across a strange behavior of Java that seems like a bug.

  • 0

I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastException even if the object is not an instance of K. Here is an example:

import java.util.*;
public final class Test {
  private static<K,V> void addToMap(Map<K,V> map, Object ... vals) {
    for(int i = 0; i < vals.length; i += 2)
      map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException!
  }
  public static void main(String[] args) {
    Map<String,Integer> m = new HashMap<String,Integer>();
    addToMap(m, "hello", "world"); //No exception
    System.out.println(m.get("hello")); //Prints "world", which is NOT an Integer!!
  }
}

Update: Thanks to cletus and Andrzej Doyle for your helpful answers. Since I can only accept one, I’m accepting Andrzej Doyle’s answer because it led me to a solution that I think isn’t too bad. I think it’s a little better way of initializing a small Map in a one-liner.

  /**
   * Creates a map with given keys/values.
   * 
   * @param keysVals Must be a list of alternating key, value, key, value, etc.
   * @throws ClassCastException if provided keys/values are not the proper class.
   * @throws IllegalArgumentException if keysVals has odd length (more keys than values).
   */
  public static<K,V> Map<K,V> build(Class<K> keyClass, Class<V> valClass, Object ... keysVals)
  {
    if(keysVals.length % 2 != 0)
      throw new IllegalArgumentException("Number of keys is greater than number of values.");

    Map<K,V> map = new HashMap<K,V>();
    for(int i = 0; i < keysVals.length; i += 2)
      map.put(keyClass.cast(keysVals[i]), valClass.cast(keysVals[i+1]));

    return map;
  }

And then you call it like this:

Map<String,Number> m = MapBuilder.build(String.class, Number.class, "L", 11, "W", 17, "H", 0.001);
  • 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-14T16:39:34+00:00Added an answer on May 14, 2026 at 4:39 pm

    As cletus says, erasure means that you can’t check for this at runtime (and thanks to your casting you can’t check this at compile time).

    Bear in mind that generics are a compile-time only feature. A collection object does not have any generic parameters, only the references you create to that object. This is why you get a lot of warning about “unchecked cast” if you ever need to downcast a collection from a raw type or even Object – because there’s no way for the compiler to verify that the object is of the correct generic type (as the object itself has no generic type).

    Also, bear in mind what casting means – it’s a way of telling the compiler “I know that you can’t necessarily check that the types match, but trust me, I know they do”. When you override type checking (incorrectly) and then end up with a type mismatch, who ya gonna blame? 😉

    It seems like your problem lies around the lack of heterogenous generic data structures. I would suggest that the type signature of your method should be more like private static<K,V> void addToMap(Map<K,V> map, List<Pair<K, V>> vals), but I’m not convinced that gets you anything really. A list of pairs basically is a map, so contructing the typesafe vals parameter in order to call the method would be as much work as just populating the map directly.

    If you really, really want to keep your class roughly as it is but add runtime type-safety, perhaps the following will give you some ideas:

    private static<K,V> void addToMap(Map<K,V> map, Object ... vals, Class<K> keyClass, Class<V> valueClass) {
      for(int i = 0; i < vals.length; i += 2) {
        if (!keyClass.isAssignableFrom(vals[i])) {
          throw new ClassCastException("wrong key type: " + vals[i].getClass());
        }
        if (!valueClass.isAssignableFrom(vals[i+1])) {
          throw new ClassCastException("wrong value type: " + vals[i+1].getClass());
        }
    
        map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException!
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have come across a lot of optimization tips which say that you should
I have come across the following type of code many a times, and I
In my work I have come across syntax like global:: (C#) or G:Loading($value) in
I'm learning about DDD, and have come across the statement that value-objects should be
I have come across a small problem. Say I have two lists: list_A =
I have come across what must be a common problem. When I have an
I have come across a quirky feature in Visual Studio and I was interested
One of the problems I have come across having complex tasks on the browser
I am a newbie to Python and have come across the following example in
I'm learning objective-C and Cocoa and have come across this statement: The Cocoa frameworks

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.