javacastingargumentstype-declaration

Java method arguments: type declaration in parentheses?


I'm implementing a LinkedListDeque data structure. I've written an equals method and a helper that:

  1. Checks if object o is an instance of class LinkedListDeque. If true,
  2. Checks if each node in o is equal to the nodes in this deque.

I wrote a helper because I needed a way to do the comparison operation in 2 between two LinkedListDeque objects and not between the this deque and the o object. When I first wrote the equals_helper method, I left out the parentheses in the type declaration. Tested, didn't work. The IDE suggested that I put a parentheses around the type declaration (i.e. equals_helper(LinkedListDeque o) to equals_helper((LinkedListDeque) o)), and that worked.

I've tried to find some documentation on what I'm doing here, but I don't have the background knowledge to know what I'm searching for. What is this concept called, am I applying it correctly in the context of Java OOP principles, and is there a better way to do this?

public boolean equals(Object o) {
    if (!(o instanceof LinkedListDeque)) {
        return false;
    } else {
        return this.equals_helper((LinkedListDeque) o);
    }
}

public boolean equals_helper(LinkedListDeque L) {
    if (L.size() != this.size()) {
        return false;
    } else {
        Node orig_curr = sentinel.next;
        Node curr = L.sentinel.next;
        while (orig_curr.item != null || curr.item != null) {
            if (orig_curr.item == curr.item) {
                curr = curr.next;
                orig_curr = orig_curr.next;
            } else return curr.next.item == null && orig_curr.next.item == null;
        }
    }
    return true;
}

Solution

  • Since the argument to equals is of type Object you need to cast it to the type that you want to use. Otherwise, it could be a different type. In this case LinkedListDeque. But as of Java 14, you can do it as follows:

    public boolean equals(Object o) {
        if (o instanceof LinkedListDeque lld)) {
           return this.equals_helper(lld);
        }
        return false;
    }
    

    If the instanceof returns true, it is automatically cast to the correct type and placed in lld which may then be used. No explicit casting is required.

    Note: You should first check to see if the objects are the same. if(this == obj) return true;

    And it's a good habit to also override hashCode when you override equals.