user5700598
user5700598

Reputation:

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 x to see if there are any people who donated blood more than 50 times. If so, that donor gets added to LinkedList y and removed from LinkList x. If no donors who donated more than 50 times are present, an empty LinkedList of y is returned.

I need the LinkedList y 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) {
            y.add(donor);
            x.remove(donor);
        }
        if (donations > number) {

        }
    }
    return y;
}

Could anyone explain why I am getting this error?

Upvotes: 1

Views: 1276

Answers (2)

eckes
eckes

Reputation: 10433

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).

Upvotes: 2

Jim Garrison
Jim Garrison

Reputation: 86774

Change

public BloodDonor heroDonors()

to

public List<BloodDonor> heroDonors()

Upvotes: 1

Related Questions