+ 2
Then you will need to use the Object class. Keep in mind that if you do so you will have to do type checking to do any actual work with the objects and their various types. (isInstanceOf() or getClass() etc) Map<Object, Object> a=new HashMap<>(); a.put(1,1); a.put(1,2); a.put(1,3); a.put(1,4); for (Map.Entry<Object, Object> i: a.entrySet()){ System.out.println(i.getKey()+" "+i.getValue()); } This will work ok here because we're just calling the objects toString() method, but for more class specific operations you'll have to check the object's type and cast it etc using polymorphism.
21st Apr 2020, 7:14 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Type inference only goes so far. You need to let the compiler know what type of objects are being used with your Map etc. There are also other ways you can do this, such as using a for each or stream. import java.util.*; class sam { public static void main(String[] args) { Map<Integer, Integer> a=new HashMap<Integer, Integer>(); a.put(1,1); a.put(1,2); a.put(1,3); a.put(1,4); for (Map.Entry<Integer, Integer> i: a.entrySet()){ System.out.println(i.getKey()+" "+i.getValue()); } } }
21st Apr 2020, 4:11 AM
ChaoticDawg
ChaoticDawg - avatar