Question about a set of generalizations (list)

I am trying to use a common technique to create objects from Xml. (Xml is deprecated, so although there are already libraries for this, it was faster to write this.)

I do not understand the compiler’s complaint about general use. Code example:

public void createObjects() {
  List<Object1> objectOnes = new ArrayList<Object1>();
  List<Object2> objectTwos = new ArrayList<Object2>();

  parseObjectsToList("XmlElement1", objectOnes);
  parseObjectsToList("XmlElement2", objectTwos);
}

private void parseObjectsToList(String xmlTag, List<? extends Object> targetList) {
   // read Xml and create object using reflection
   Object newObj = createObjectFromXml(xmlTag);
   targetList.add(newObj)  

/* compiler complains: "The method add(capture#2-of ? extends Object) in the type List<capture#2-of ? extends Object> is not applicable for the arguments (Object)" 
*/

/* If I change method signature to parseObjectsToList(String xmlTag, List targetList)
it works fine, but generates compiler warning about raw type */

}

Thanks for any enlightenment on this!

+3
source share
4 answers

Use List<Object>will work, but you may need to type more accurately List<Object1>and List<Object2>for type safety elsewhere. In this case, you will need to check the type of each object before adding it to List.

private void parseObjectsToList(String tag, List<T> list, Class<? extends T> c) {
   // read Xml and create object using reflection
   Object newObj = createObjectFromXml(tag);
   list.add(c.cast(newObj))  ;
}

cast() : (T) newObj

:

parseObjectsToList("XmlElement1", objectOnes, Object1.class);
+1

, , , , , - . :

List<? extends Shape > - .? , , . , Shape. (: - , .) , Shape .

, , . ,

+4

, T List, parseObjectsToList, Object. , List .

, List<T> ( targetList), targetList.add(Object). , Object T.

List, , List<Object> , , .

+2

, :

  • "-, Object
  • Let me paste Objectin it

This makes no sense. Suppose your list is a list Integer. Suppose that createObjectFromXmlreturns a String. It would be pointless to allow insertion Stringinto the list typed for Integers.

So, your options are either to make your list a List<Object>, or to find a way to createObjectFromXmlreturn a certain type, which you can then bind to the type of your list.

+1
source

Source: https://habr.com/ru/post/1751798/


All Articles