0

I'm currently studying collections and while I was changing a code from generics to without generics and I came into the looping of a none generic collection, how can I loop the collection without generics in the code below? Is there any way that I can know what is the type of an object in a collection without generics?


import java.util.Iterator;
import java.util.TreeSet;

public class Forest4 {
    private String name;
    private String county;
    private TreeSet trees;

    public Forest4(String n, String c) {
        name = n;
        county = c;
        trees = new TreeSet();
    }

    public String getname() {
        return name;
    }

    public String getcounty() {
        return county;
    }

    public TreeSet gettrees() {

        return trees;
    }

    public void setname(String x) {
        name = x;
    }

    public void setcounty(String x) {
        county = x;
    }

    public void settrees(TreeSet b) {

        trees = b;
    }

    public void AddTree(Tree T) {

        trees.add(T);
    }

    public void FindTree(Tree T) {
        if (trees.contains(T)) {
            T.print();

        } else {
            System.out.println(" An" + T.getname() + "tree is not found in the forest");
        }

    }

    public void RemoveFruitfulTrees_foreach() {
        for (Tree y : trees) {
            if (y.getfruitful() == true) {
                trees.remove(y);
            }
        }

    }

    /*
     * public void RemoveFruitfulTrees_forloop(){ for(int i=0;i<trees.size();i++){
     * 
     * Tree y=trees.get(i); if(y.getfruitful()==true){ trees.remove(y); } }
     * 
     * }
     */
    public void RemoveFruitfulTrees_iterator() {

        Iterator<Tree> b;
        b = trees.iterator();

        while (b.hasNext() == true) {
            Tree c = b.next();
            if (c.getfruitful() == true) {
                trees.remove(c);
            }
        }
    }

}

The error was "Type mismatch: cannot convert from element type Object to Tree" in this snippet

    public void RemoveFruitfulTrees_foreach() {
        for (Tree y : trees) {
            if (y.getfruitful() == true) {
                trees.remove(y);
            }

Thanks in advance!

GamerToonz
  • 51
  • 4
  • try `private TreeSet trees;` and use diamond (`<>`) operator in constructor! ..but it ist *not* "without generics".(?) – xerx593 May 03 '21 at 22:04

1 Answers1

1

You're creating your TreeSet the wrong way, it has no type.

TreeSet<Tree> trees = new TreeSet<>();

(btw. nice pun!)

maio290
  • 6,440
  • 1
  • 21
  • 38