-2

It may be a really stupid question , I have a java code which is as follows :

public Collection<Object> getCollection(){
     List<Map<String,Object> listMap = getListMap();
     return listMap;
}

I am getting an exception saying

cannot assign a value of Java.util.list<java.util.map<java.lang.String,java.lang.Object>>  
to java.util.Collection<java.lang.Object> 

Of course the error must be valid , But why is that ? And how can i overcome this ?

Bibin Mathew
  • 203
  • 3
  • 15
  • 3
    A `Collection` can have any `Object` put into it. A `List` can only have maps put into it. You can get it to compile just by casting away the generics, but it really depends what you're trying to do. – khelwood Feb 07 '17 at 10:18
  • 2
    have a look at [this](http://stackoverflow.com/q/2745265/2764279) question. – earthmover Feb 07 '17 at 10:21
  • 2
    Java's generic types does not follows inheritance rules – cybersoft Feb 07 '17 at 10:22
  • This error seems not matching with the exposed code. I would expect to "cannot convert..." but not "cannot assign" – davidxxx Feb 07 '17 at 10:23
  • Okay , I am very weak in generics ideally from my understanding this would have worked. Anyways , i will cast it for now. Thank you – Bibin Mathew Feb 07 '17 at 10:23
  • 1
    Possible duplicate of [Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – Tom Feb 07 '17 at 10:29

3 Answers3

1

When using generics, avoid using references to Object. Instead use the wild card ? For example, in your case, change the Collection<Object> to Collection<?>.

So your method becomes,

public Collection<?> getCollection(){
     List<Map<String,Object>> listMap = getListMap();
     return listMap;
}

Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31
0

change your method signature to Collection<Map<String,Object>>

 public Collection<Map<String,Object>> getCollection(){
     List<Map<String,Object>> listMap = getListMap();
     return listMap;
}
Sasikumar Murugesan
  • 4,412
  • 10
  • 51
  • 74
0

This Material will be useful for understanding generics Inheritance: Java Documentation . Try this (it should work fine):

public Collection<Object> getCollection() {
    return new ArrayList<>(getListMap());
}
Petya
  • 312
  • 2
  • 6