4

I received an error when compiled the code below, which is "incomparable types: int and " on line 10.

public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    if (nums == null || k <= 0 || t < 0 || nums.length < 2) return false;

    TreeSet<Integer> set = new TreeSet<>();
    for (int i = 0; i < nums.length; i++) {
        int floor = set.floor(nums[i] + t);//return largest number smaller than nums[i] + t or null
        int ceil = set.ceiling(nums[i] - t);//return least number larger than num[i] - t or null

        if ((floor != null && floor >= nums[i]) || (ceil != null && ceil <= nums[i])) {
            return true;
        }

        set.add(nums[i]);

        if (set.size() > k) {
            set.remove(nums[i - k]);
        }
    }

    return false;
}}

but if I add final keyword before treeset, floor and ceil, the code will be compiled successfully. Could anyone help me explain what's going on? Thanks.

...
final TreeSet<Integer> set = new TreeSet<>();
for (int i = 0; i < nums.length; i++) {
    final Integer floor = set.floor(nums[i] + t);//return largest number smaller than nums[i] + t or null
    final Integer ceil = set.ceiling(nums[i] - t);//return least number larger than num[i] - t or null
...
OhhhIrisHere
  • 43
  • 1
  • 3

2 Answers2

8

int floor defines floor as a basic int type. Integer floor defines floor as a non-trivial, class type. null is used only with non-trivial types

Ripi2
  • 7,031
  • 1
  • 17
  • 33
0

It has nothing to do with the final keyword (It will work without it anyway). You just can't compare a primitive value (int) to null. Instead, you should use a corresponding object (Integer).

Terry Li
  • 16,870
  • 30
  • 89
  • 134