Search code examples
javaarraylistbinary-treeunsafeunchecked

Unsafe or unchecked expressions in an arraylist


I'm doing an assignment and I have to create an iterable collection that saves all values of a binary tree between certain tresholds. The binary tree class has a root variable, which is an object of a TreeNode class I've written. The nodes only store integer values. Here are my methods:

public class Tree {
    public Iterable<Integer> listing(int low, int high) {
            ArrayList<Integer> list=new ArrayList<Integer>();
                 return root.listing(lo, hi, list);
        }
}

public class TreeNode {
    public ArrayList<Integer> listing(int low, int high, ArrayList list) {
        if(this.left!=null) {
            list=this.left.listing(low, high, list);
        }

        if(this.value>=low && this.value<=high) {
            list.add(this.value);
        }

        if(this.right!=null) {
            list=this.right.listing(low, high, list);
        }
        return list;
    }
}

It works perfectly fine locally, but I have to upload it to a platform which uses Java 6, and I'm getting an error that it uses unchecked or unsafe operations. I am getting the same message in my IDE, but it seems to imply that it's not of great importance. However, I have to fix this in some way. I tried reading up on unsafe/unchecked operations but I'm not sure I really do understand what's the problem here. Is there any way to fix this without changing the whole code?


Solution

  • This isn't an error, it's a warning, but, as you noted, you should probably fix it.

    The problem is that you're passing an unbound ArrayList, that, theoretically, can hold elements of any type, while you're only dealing with Integers. So, instead, you could declare your parameter as an ArrayList of Integers:

    public ArrayList<Integer> listing(int low, int high, ArrayList<Integer> list) {
    

    Edit:
    By the way, there's no need to have an ArrayList in the method's declaration. Since the only thing you care about here is List interface and not it's implementation, you can clear up the declaration a bit:

    public List<Integer> listing(int low, int high, List<Integer> list) {