'Cannot resolve method 'equals(long)'

I'm working on a spring boot application. However in my service impl class I'm getting a "Cannot resolve method 'equals(long)' when I try to use the equals() method. Any ideas on what the issue my be and how to fix it. Here is part of my service class:

    @Override
    public CommentDto updateComment(Long postId, long commentId, CommentDto commentRequest) {
        // retrieve post entity by id
        Post post = postRepository.findById(postId).orElseThrow(
                () -> new ResourceNotFoundException("Post", "id", postId));

        // retrieve comment by id
        Comment comment = commentRepository.findById(commentId).orElseThrow(() ->
                new ResourceNotFoundException("Comment", "id", commentId));

        if(!comment.getPost().getId().equals(post.getId())){
            throw new BlogApiException(HttpStatus.BAD_REQUEST, "Comment does not belongs to post");
        }

        comment.setName(commentRequest.getName());
        comment.setEmail(commentRequest.getEmail());
        comment.setBody(commentRequest.getBody());

        Comment updatedComment = commentRepository.save(comment);
        return mapToDTO(updatedComment);
    }



Solution 1:[1]

Presumably, the compilation error is on this line:

if (!comment.getPost().getId().equals(post.getId())) {

From the error message, we can infer that post.getId() returns long, and that the comment.getPost().getId() expression has a static (reference) type that doesn't provide an equals(long) or equals(Long) method. (It most likely just has the equals(Object) inherited from Object.)

So ... assuming you are actually intending to do an integer equality test here ... there are a couple of ways to do this:

This one will work if the return type of comment.getPost().getId() is a subtype of Number

if (comment.getPost().getId().longValue() != post.getId())) {

This will only work if the return type is Long:

if (!comment.getPost().getId().equals(Long.valueOf(post.getId()))) {

You could also solve this by being consistent about the return types of your (at least two) getId() methods. (Why does one return long and the other something reference type? You are doing the same thing in the updateComment method signature.)


Note that this is NOT a solution:

if (comment.getPost().getId() != Long.valueOf(post.getId())) {

You should not use == to compare 2 values whose type are a wrapper class; i.e. Boolean, Byte, Short, Character, Integer, Long, Float or Double. The == operator will compare references, and that may give the wrong answer ... if your intention is to compare numeric values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1