Search code examples
javacoldfusionlucee

Java method in Coldfusion gives double the correct answer


Well, I partly answered the question. The commas that I thought were separators in the list we being counted as part of the string. So the question becomes -- is there a better way to set up a Java list?

Here is the code:

<cfset objString = CreateObject(
"java",
"java.lang.String"
).Init(
    JavaCast(
        "string",
        "s,s,s,n,n,n"
        )
    )
/>

<cfset objString = objString.lastIndexOf('n') />

<cfoutput>
#objString#
</cfoutput>

The answer should be 5 but I get 10. Every other answer is also doubled, both with this method and the IndexOf() method. Can someone tell me how to fix this (besides dividing my answer by 2) and/or what is going on?

The lastIndexOf() method is working in generic ColdFusion without any Java code. But I am trying to convert that code to Lucee, which does not recognize the lastIndexOf() method. The above code works in Lucee exactly as in Coldfusion -- that is it is giving me double the correct answer.


Solution

  • You are getting double the results as the comma(,) are counted as well because the list has been passed as a string.

    String class has a constructor that accepts a char array i.e., String(char[] value) so, you can try this:

    <!--- Comma delimited list --->
    <cfset local.myList = "s,s,s,n,n,n">
    
    <!--- Convert list to array --->
    <cfset local.myCharArray = listToArray(local.myList, ",")>
    
    <!--- Create String object using String(char[] value) contructor --->
    <cfset local.objString = createObject(
                                "java",
                                "java.lang.String"
                             ).init( 
                                  javaCast( "char[]", local.myCharArray )
                               )>
    
    <!--- Get last index --->
    <cfset local.lastIndex = local.objString.lastIndexOf('n') />
    
    <!--- Output: 5 --->
    <cfoutput>#local.lastIndex#</cfoutput>
    

    Here is the TryCF.

    Another approach using ArrayList for working with list of string:

    <!--- Comma delimited list --->
    <cfset local.myList = "s,s,s,no,not,no">
    
    <!--- Convert list to array --->
    <cfset local.myCharArray = listToArray(local.myList, ",")>
    
    <!--- Create ArrayList Object --->
    <cfset local.objArrayList = createObject(
                                    "java",
                                    "java.util.ArrayList"
                                ).init( 
                                    javaCast( "int", arrayLen(local.myCharArray) ) )>
    
    <!--- Add item(s) --->
    <cfset local.objArrayList.addAll(local.myCharArray)>
    
    <!--- Get last index --->
    <cfset local.lastIndex = local.objArrayList.lastIndexOf("no") />
    
    <cfoutput>#local.lastIndex#</cfoutput>
    

    Here is the TryCF.