views:

53

answers:

4

Hi folks!

I've got a problem with java's instanceof. Here's a gap of code that causes me trouble:

LinkedList<Double> currentSummary = summary.getFirst().getQuantiles();

...more code...

while (!currentSummary.isEmpty()){

        if (currentSummary.getFirst() instanceof Double){
            orderedSummary.add(new ComparableWrapper<Double, Float>(currentSummary.removeFirst(), currentEpsilon));
        }
}

So, my problem is, that the if-condition won't become true. Those elements in currentSummary are either null or an Double-value. And I'm trying to reject elements that are null. At first I just added them and ran into NullPointerException later on, because of some (but not all!) elements being null. An example element of currentSummary is e.g. [null, 0.09861866469135272, 10.137051035535745, 107.12083740100329, 371.4371264801424, 827.432799544501, 1206.251577083686].

Anybody got's an idea why instanceof won't work in that case? I tried it with currentSummary.getFirst() instanceof Object as well...

Thanks in advance!

A: 

Is it possible that due to auto-boxing/unboxing, the Double objects get unboxed to the primitive double, and therefore they are not instance of Double class.

If that is the case, would it be better if you check for non-null elements instead?

ejel
Neither autoboxing nor autounboxing happens for an instanceof test.
Christian Semrau
A: 

Why don't you just use a simple null check?

if (currentSummary.getFirst() != null){ ... }
Tim Bender
I agree, but this doesn't explain why instanceof returns false for non-null values.
Eyal Schneider
That doesn't seem to work at first. But you're right, that would work as well and looks much better ;) Thanks
kkm
+2  A: 

I assume you want to remove the first entry at each iteration, in order to traverse the complete list. However, you remove the entry only when the instanceof condition is true. Therefore, it seems like the loop becomes infinite when it encounters the first null value (unless you dropped parts of the code, and we don't see the complete loop body)

Eyal Schneider
Okay, it's definitely to warm at my place. The problem was of course the infinity-loop -.- Thanks a lot :)
kkm
A: 

It is possible, by using raw types (LinkedList instead of LinkedList<Double>), to add non-Double entries to your LinkedList<Double>. Those elements would fail the instanceof Double test. But those entries would pass an instanceof Object test.

Christian Semrau