Convert Map to Map

后端 未结 11 1840
暗喜
暗喜 2021-01-31 13:27

How can I convert Map to Map ?

This does not work:

Map map = ne         


        
11条回答
  •  一整个雨季
    2021-01-31 14:00

    While you can do this with brute casting and suppressed warnings

    Map map = new HashMap();
    // Two casts in a row.  Note no "new"!
    @SuppressWarnings("unchecked")
    Map newMap = (HashMap)(Map)map;  
    

    that's really missing the whole point. :)

    An attempt to convert a narrow generic type to a broader generic type means you're using the wrong type in the first place.

    As an analogy: Imagine you have a program that does volumous text processing. Imagine that you do first half of the processing using Objects (!!) and then decide to do the second half with correct-typing as a String, so you narrow-cast from Object to String. Fortunately, you can do this is java (easily in this case) - but it's just masking the fact you're using weak-typing in the first half. Bad practice, no argument.

    No difference here (just harder to cast). You should always use strong typing. At minimum use some base type - then generics wildcards can be used ("? extends BaseType" or "? super BaseType") to give type-compatability and automatic casting. Even better, use the correct known type. Never use Object unless you have 100% generalised code that can really be used with any type.

    Hope that helps! :) :)


    Note: The generic strong typing and type-casting will only exist in .java code. After compilation to .class we are left with raw types (Map and HashMap) with no generic type parameters plus automatic type casting of keys and values. But it greatly helps because the .java code itself is strongly-typed and concise.

提交回复
热议问题