0

I'm trying to create a TreeSet in objc using the J2ObjC cocoapod package v0.9.6.1 (the latest at this time).

#include <java/util/TreeSet.h>

    id<JavaUtilSet> set = [[JavaUtilTreeSet alloc] init];
    for (NSString* setval in (NSArray*)values) {
        [set addWithId:setval];  // <== JavaLangClassCastException
    }

However, this throws an exception:

JavaLangClassCastException: java.lang.String is not Comparable

indicating that the NSString (there is no separate JavaLangString in j2objc) won't cast to a Comparable object. The exception is thrown from

JavaUtilTreeMap findWithId:withJavaUtilTreeMap_RelationEnum:

A previous 0.9 version (8ee9dc12ad) worked just fine with my above code. If I change JavaUtilTreeSet to be JavaUtilHashSet then it works.

Is this a bug in v0.9.6.1 of J2ObjC or am I doing something wrong here?

Brian White
  • 8,332
  • 2
  • 43
  • 67

3 Answers3

0

I think you need to include NSString+JavaString.h (it's a j2objc public header), as that defines the NSString category which adds the Comparable protocol. Otherwise those NSString objects are just NSStrings. :-)

tball
  • 1,984
  • 11
  • 21
  • I've tried that and it doesn't make any difference in my build, nor does including the full "JreEmulation.h" file. Perhaps it needs to be included by the JavaUtilTreeMap module that is part of the pre-built library? – Brian White Jul 21 '17 at 14:22
0

TreeSet works, as this example shows:

import java.util.*;

class TreeSetTest {
  public static void main(String... args) {
    Set<String> set = new TreeSet<>();
    for (String setval : args) {
      set.add(setval);
    }
    System.out.println(set);
  }
}

$ j2objc TreeSetTest.java
$ j2objcc TreeSetTest.m
$ ./a.out TreeSetTest Tom Dick Harry
[Dick, Harry, Tom]

A lot of headers were included in TreeSetTest.h and TreeSetTest.m, so I encourage you to translate this example and see what's generated. The "java/io/PrintStream.h" and "java/lang/System.h" aren't needed for your code since that's to support the System.out line, but including the others won't hurt and may fix your problem.

tball
  • 1,984
  • 11
  • 21
0

It turns out that the version in Cocoapods is about 2 years out of date, if not more. The latest J2ObjC is v2.0.2 and after switching to that (non-pod) version, the TreeSet again works.

So I conclude it's a bug in that specific (old) version.

Brian White
  • 8,332
  • 2
  • 43
  • 67