Filip Grebowski Filip Grebowski - 2 months ago 18
Java Question

java.util.LinkedList<ClassName> cannot be converted to ClassName

I am on my way to learning java, so please bear with me on this one, even if its very simple to you.

I'm working with two LinkedLists:

private LinkedList<BloodDonor> x;
private LinkedList<BloodDonor> y;

public List()
x = new LinkedList<>();
y = new LinkedList<>();

I have a method called heroDonors that searches the LinkedList
to see if there are any people who donated blood more than 50 times. If so, that donor gets added to LinkedList
and removed from LinkList
. If no donors who donated more than 50 times are present, an empty LinkedList of
is returned.

I need the LinkedList
to be returned by the method, but I get the error
java.util.LinkedList<BloodDonor> cannot be converted to BloodDonor

public BloodDonor heroDonors()
int donations = 50;
for (BloodDonor donor : x) {
int number = donor.getNumberOfDonations();
if (donations < number) {
if (donations > number) {

return y;

Could anyone explain why I am getting this error?


If you want to return a List of BloodDonors you have to actually make your method of that type:

public LinkedList<BloodDonor> heroDonors() {
    LinkedList<BloodDonor> result = new LinkedList<>();
    return result;

BTW: I think in this case you should not use a field y but declare a local variable on order to avoid side effects. You might also consider returning the base type List<BloodDonor> instead, this will better allow to use another collection if needed (and I would never call a application class List).