how can i loop through object which extends from a class? i give an example: I have an Abstract class (AbstractDTO) and 2 classes which extends AbstractDTO:
public abstract class AbstractDTO
{
private int id;
/**
* @return the id
*/
public int getId()
{
return id;
}
/**
* @param id the id to set
*/
public void setId(int id)
{
this.id = id;
}
}
public class FirstDTO extends AbstractDTO
{
}
public class SecondDTO extends AbstractDTO
{
}
Now i got a method which excpects 2 Collections of objects which extends AbstractDTO. I want to add all objects of the second list to the first list, if they are not in the first list already. how can i do this?
i tried the following:
public static void summarizeCollection(List<? extends AbstractDTO> firstList, Set<? extends AbstractDTO> secondList)
{
for(AbstractDTO second : secondList)
{
boolean exists = false;
for (AbstractDTO first : firstList)
{
if (second.getId() == first.getId())
{
exists = true;
}
}
if(!exists)
{
firstList.add(second);
}
}
}
I got an error in the line " firstList.add(second);" cause my second object is of the type AbstractDTO and not of a class which extends AbstractDTO.
Can someone help me with that? Thx alot ;)
The compiler cannot be sure that the elements in secondList
are of the same type of the elements declared in firstList
, thus you get a compiler error here:
firstList.add(second);
This is caused for the definition of the arguments:
List<? extends AbstractDTO> firstList, Set<? extends AbstractDTO> secondList
If you're sure both List
and Set
are of the same type and this type extends AbstractDTO
, then declare your method like this:
public static <T extends AbstractDTO> void summarizeCollection(List<T> firstList, Set<T> secondList)
Then, inside the method, change this for
loop:
for(AbstractDTO second : secondList)
into
for(T second : secondList)
And on.
More info:
The compiler error is there because the compiler cannot guarantee that the wildcard from the List
is equal to the wildcard from the Set
.
You can solve this by making the method generic. You need a type variable to represent the type of the List
, which must be an AbstractDTO
, say T
. You can make the Set
a wildcard bounded by T
, so that a Set
of any type that is T
or extends T
can have its elements added to the List
.
public static <T extends AbstractDTO> void summarizeCollection(
List<T> firstList, Set<? extends T> secondList)
Then both for
loops' variables should be of type T
.
for(T second : secondList)
and
for (T first : firstList)
This will allow the call to add
to compile.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.