简体   繁体   中英

Type mismatch: cannot convert from element type Object to Parent

i'm trying to develop an e4 application but i have an error : in this part "error:Type mismatch: cannot convert from element type Object to Parent" any help please thanks in advance :)

@Creatable
@Singleton
public class TreeControl {
    ParentsHolder parentholder = new ParentsHolder();

    public Parent parentExists(String str) {
        for (Parent p : parentholder.getParents())
            if (p.getTag().equals(str))
                return p;
        return null;
    }

    public Child childExists(String p, String c) {
        Parent parent = parentExists(p);
        if (parent != null)
            for (Child child : parent.getChildren())
                if (child.getTag().equals(c))
                    return child;
        return null;
    }
}

this is Parent Holder class

public class ParentsHolder extends Model {
    List parents = new ArrayList();

    public List getParents() {
        return parents;
    }

    public void setParents(List parents) {
        firePropertyChange("parents", this.parents, this.parents = parents);
    }

        public void addParent(Parent p) {
            List newlist = new ArrayList<>(parents);
            newlist.add(p);
            setParents(newlist);
        }
    }

and the error is in this line

for (Parent p : parentholder.getParents())

and this line:

   for (Child child : parent.getChildren())

You are just using the 'raw type' List for your list so Java does not know that this is a list of Parent objects and can only treat it as a list of Object .

You need to use generics to specify the list type - everywhere you have List it should be List<Parent> .

So something like:

public class ParentsHolder extends Model {
    List<Parent> parents = new ArrayList<>();

    public List<Parent> getParents() {
        return parents;
    }

    public void setParents(List<Parent> parents) {
        firePropertyChange("parents", this.parents, this.parents = parents);
    }

    public void addParent(Parent p) {
        List<Parent> newlist = new ArrayList<>(parents);
        newlist.add(p);
        setParents(newlist);
    }
}

change corresponding lines to below code as:

for(Object p : parentholder.getParents())
      {
          Parent p1= (Parent)p;
           //your code .....
        }

similarily for Child class

 for(Object p : parentholder.getParents())
      {
          Child child= (Parent)p;
           //your code .....
        }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM