2013-05-03 10 views
7

मेरे पास एक विधि है जो पैरामीटर के रूप में Map<Integer, Set<Object>> लेती है। Map<Integer, Set<String>> और पैरामीटर के रूप में Map<Integer, Set<Integer>> का उपयोग करके, मुझे इसे दो अलग-अलग स्थानों से कॉल करने की आवश्यकता है।मानचित्र कास्टिंग <इंटीजर, सेट <Object>>

संकलक शिकायत इसलिए मैंने विधि पैरामीटर हस्ताक्षर Map<Integer, ?> पर बदल दिया, और अब मैं इसे कॉल कर सकता हूं, लेकिन अलग-अलग समस्याएं हैं।

private void methodA (Map<Integer, ?> inOutMap, Integer key, Object value) { 

     Set<Object> list = new HashSet<Object>(); 

     if (!inOutMap.containsKey(key)) { 
      list.add(value); 
     } else { 
      list = (Set<Object>) (Set<?>) inOutMap.get(key); //I wrote the cast, but looks quite ugly 
      list.add(value); 
     } 

     inOutMap.put(key, list); //compiler error 
     //The method put(Integer, capture#4-of ?) in the type Map<Integer,capture#4-of ?> is not applicable for the arguments (Integer, Set<Object>) 
    } 

वहाँ संकलक त्रुटि के हल के लिए कोई तरीका है: विधि मूल रूप से इस प्रकार है? यह है, list? कास्टिंग।

मेरा दूसरा प्रश्न वैचारिक है। क्या अलग-अलग पैरामीटर हस्ताक्षर के साथ दो अलग-अलग तरीकों को लिखने के अलावा ऐसा करने का कोई बेहतर तरीका है?

उत्तर

7

रूप

private <T> void methodA (Map<Integer, Set<T>> inOutMap, Integer key, T value) { 

     Set<T> list = new HashSet<T>(); 

     if (!inOutMap.containsKey(key)) { 
      list.add(value); 
     } else { 
      list = inOutMap.get(key); 
      list.add(value); 
     } 

     inOutMap.put(key, list); 
    } 

इसका यह घोषणा हमेशा जेनेरिक्स उपयोग करने के लिए अच्छा है जब आप,

अब आप आह्वान कर सकते हैं बहस के कई प्रकार का उपयोग करने के लिए कोशिश कर रहे हैं Object या ? (अज्ञात प्रकार) का उपयोग करने से Set का उपयोग कर एक ही विधि

Map<Integer, Set<String>> m1 = new HashMap<Integer, Set<String>>(); 
Map<Integer, Set<Integer>> m2 = new HashMap<Integer, Set<Integer>>(); 

methodA(m1, 1, "t"); 
methodA(m2, 2, 2); 
1

यह त्रुटियों के बिना और स्पष्ट कास्टिंग बिना

private <T> void methodA (Map<Integer, Set<T>> inOutMap, Integer key, T value) { 
    Set<T> list = new HashSet<T>(); 
    if (!inOutMap.containsKey(key)) { 
     list.add(value); 
    } else { 
     list = inOutMap.get(key); 
     list.add(value); 
    } 
    inOutMap.put(key, list); 
} 
0

आप इसे इस प्रकार परिभाषित नहीं किया जा सकता संकलित?

Map<Integer, Set<Object>> 
संबंधित मुद्दे