String compare using S .equals() and ==

When comparing strings, what is the different between using stringx.equals(stringy) and stringx == stringy?
And what is the different between threads that are created by implement Thread or extends Runnable.
They both work fine in my application

When comparing strings, what is the different between
using stringx.equals(stringy) and stringx ==
stringy?
And what is the different between threads that are
created by implement Thread or extends Runnable.
They both work fine in my applicationactually the equals method has been overridden to String class so that it gives you true when ever two String object contains the same String value whether the == gives you true only when two objects are same. here I guess two objects are same so you are getting true in both cases.
for the second answer it is generally depending upon your requirement to adopt one of the ways. Sometimes you are forced to implement runnable because you may have already Extends another class. Personally I felt its more often that we implements Runnable than extending the Thread class
Message was edited by:
tanmoy_rajguru
Message was edited by:
tanmoy_rajguru

Similar Messages

  • Comparator question - changing Equals and HashCode too?

    Hi all I have an object test - this contains 2 variables:
    Int a; and Int b;Then there is a method called test() which returns a double and looks like this:
    public Double test()
    return a * (1d / b);
    }I have implemented the compareTo method do the "compareTo" test using the call to test() not on the fields directly e.g.
    this.test().compareTo(anotherObject.test()) instead of
    if (this.a != null && anotherDateInterval.a != null)
                compareTo = this.a.compareTo(anotherDateInterval.a);
            }Because I using the test() in the compareTo do I need to change the equals and hashcode method as well to reflect the use of test()?
    e.g.
    public boolean equals(Object obj)
       if (test() == null)
                if (other.test() != null)
                    return false;
            else if (!test().equals(other.test()))
                return false;
    }

    That depends if there are any class invarients that can be depended upon.
    The basic rule is that if .equals() returns true, then .compareTo() must return 0, but not necessarily the other way around. As long as this holds true, you don't really have to change .equals() or .hashCode(). If you're still using the identity equals method, then you probably don't have to worry about it. If you've overridden .equals() to be dependent upon a and b in some way, you probably do have to change the way .equals() works to make sure that .equals() doesn't return true if .compareTo() doesn't return 0.
    - Adam

  • How to compare two strings whether both are equal while ignoring the difference in special characters (example: & vs & and many others)?

    I attempted to compare two strings whether they are equal or not. They should return true if both are equal.
    One string is based on Taxonomy's Term (i.e. Term.Name) whereas other string is based on String object.
    The problem is that both strings which seem equal return false instead of true. Both string values have different special characters though their special characters are & and &
    Snapshot of different design & same symbols:
    Is it due to different culture or language?
    How to compare two strings whether both are equal while ignoring the difference in special characters (& vs &)?

    Hi Jerioon,
    If you have a list of possible ambiguous characters the job is going to be easy and if (& vs &) are the only charracters in concern awesome.
    You can use the below solution.
    Before comparing pass the variables through a replace function to standarize the char set.
    $Var = Replace($Var,"&","&")
    This is going to make sure you don't end up with ambiguous characters failing the comparison and all the char are "&" in this case.
    Similar technique is used to ignore Character Cases 'a' vs. 'A'
    Regards,
    Satyajit
    Please “Vote As Helpful”
    if you find my contribution useful or “Mark As Answer” if it does answer your question. That will encourage me - and others - to take time out to help you.

  • Comparing dynamic fields of objects using equals and hashCode methods

    To compare the different objects of the same class with their contents like jobTitleId, classificationId, deptId & classificationId was to be done and do some manipulations later using Set and Map. I was able to do that by simply overriding the equals and hashCode methods of Object class and was able to fetch the information (like in the following Map).
        Map<LocationData, List<LocationData>>
    The following is the class I used (its been shown to you so that it can be referred for my problem statement):
    LocationData class
        package com.astreait.bulkloader;
        public class LocationData {    
            String locId, deptId, jobTitleId, classificationId;
            @Override  
            public boolean equals(Object obj) {        
                LocationData ld = (LocationData)obj;       
                return this.deptId.equals(ld.deptId) && this.jobTitleId.equals(ld.jobTitleId) && this.classificationId.equals(ld.classificationId) &&
        this.locId.equals(ld.locId);   
            @Override  
            public int hashCode() {        
                return deptId.hashCode() + jobTitleId.hashCode() + classificationId.hashCode() +locId.hashCode();  
    Problem:
    I'm already known to which all fields of this object I need to make the comparison.
    i.e I'm bound to use the variables named classificationId, deptId, jobTitleId & locId etc.
    Need:
    I need to customize this logic such that the fields Names (classificationId, deptId, jobTitleId & locId etc) can be pulled dynamically along with their values. So, as far as my understanding I made use of 2 classes (TableClass and ColWithData) such that the List of ColWithData is there in TableClass object.
    I'm thinking what if I override the same two methods `equals() & hashCode();`
    such that the same can be achieved.
        TableClass class #1
        class TableClass{
            List<ColWithData> cwdList;
            @Override
            public boolean equals(Object obj) {
                boolean returnVal = false;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be compared
                return returnVal;
            @Override
            public int hashCode() {
                int returnVal = 0;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be found for their individual hashCodes
                return returnVal;
    ColWithData class #2
        class ColWithData{
            String col; // here the jobTitleId, classificationId, deptId, locId or any other more fields info can come.
            String data; // The corresponding data or value for each jobTitleId, classificationId, deptId, locId or any other more fields.
    Please let me know if I'm proceeding in the right direction or I should make some any other approach. If it is ok to use the current approach then what should be performed in the equals and hashCode methods?
    Finally I need to make the map as: (Its not the concern how I will make, but can be considered as my desired result from this logic)
        Map<TableClass, List<TableClass>> finalMap;

    Hello,
    What is the relation with the Oracle Forms tool ?
    Francois

  • Trying to compare string array using equals not working

    Hi,
    im prolly being really dumb here, but i am trying to compare 2 string arrays using the following code:
    if(array.equals(copymearray))
    System.out.println("they match");
    else
    {System.out.println("dont match");}
    the trouble is that even though they do match i keep getting dont match, can anyone tell me why?

    try
    if (Arrays.equals(array, copymearray))
    System.out.println("they match");
    else
    {System.out.println("dont match");}

  • [svn] 1751: Bug: BLZ-174 - MessageClient.testMessage() is incorrectly doing a string compare for the subtopic header of an inbound message against the subtopic value (which may contain wildcards) that the Consumer is using.

    Revision: 1751
    Author: [email protected]
    Date: 2008-05-15 14:21:43 -0700 (Thu, 15 May 2008)
    Log Message:
    Bug: BLZ-174 - MessageClient.testMessage() is incorrectly doing a string compare for the subtopic header of an inbound message against the subtopic value (which may contain wildcards) that the Consumer is using.
    QA: No - customer verified the fix.
    Doc: No
    Ticket Links:
    http://bugs.adobe.com/jira/browse/BLZ-174
    Modified Paths:
    blazeds/branches/3.0.x/modules/core/src/java/flex/messaging/MessageClient.java
    blazeds/branches/3.0.x/modules/core/src/java/flex/messaging/services/MessageService.java

    If you create a metadatatype with a single metdata block, and you reference that in your vm/cm cell attribute using a *one* based index, Excel seems to see the link and it honors it when saving the spreadsheet.
    So, I ended up with something like:
    <c ... cm="1"/> (I'm dealing with cell metadata, but the concept is equivalente to value metadata)
    <metadataTypes count="1">
      <metadataType name="MyMetaType" .../>
    </metadataTypes>
    <futureMetadata count="1" name="MyMetaType">
      <bk>
        <extLst><ext
    uri="http://example" xmlns:x="http://example"><x:val>87</x:val></ext></extLst>
      </bk>
    </futureMetadata>
    <cellMetadata count="1">
      <bk><rc
    t="1" v="0"/></bk> <!-- this is what gets referenced as cm=1 on the cell -->
    </cellMetadata>
    Hope this helps. 

  • How to Compare 2 CSV file and store the result to 3rd csv file using PowerShell script?

    I want to do the below task using powershell script only.
    I have 2 csv files and I want to compare those two files and I want to store the comparision result to 3rd csv file. Please look at the follwingsnap:
    This image is csv file only. 
    Could you please any one help me.
    Thanks in advance.
    By
    A Path finder 
    JoSwa
    If a post answers your question, please click &quot;Mark As Answer&quot; on that post and &quot;Mark as Helpful&quot;
    Best Online Journal

    Not certain this is what you're after, but this :
    #import the contents of both csv files
    $dbexcel=import-csv c:\dbexcel.csv
    $liveexcel=import-csv C:\liveexcel.csv
    #prepare the output csv and create the headers
    $outputexcel="c:\outputexcel.csv"
    $outputline="Name,Connection Status,Version,DbExcel,LiveExcel"
    $outputline | out-file $outputexcel
    #Loop through each record based on the number of records (assuming equal number in both files)
    for ($i=0; $i -le $dbexcel.Length-1;$i++)
    # Assign the yes / null values to equal the word equivalent
    if ($dbexcel.isavail[$i] -eq "yes") {$dbavail="Available"} else {$dbavail="Unavailable"}
    if ($liveexcel.isavail[$i] -eq "yes") {$liveavail="Available"} else {$liveavail="Unavailable"}
    #create the live of csv content from the two input csv files
    $outputline=$dbexcel.name[$i] + "," + $liveexcel.'connection status'[$i] + "," + $dbexcel.version[$i] + "," + $dbavail + "," + $liveavail
    #output that line to the csv file
    $outputline | out-file $outputexcel -Append
    should do what you're looking for, or give you enough to edit it to your exact need.
    I've assumed that the dbexcel.csv and liveexcel.csv files live in the root of c:\ for this, that they include the header information, and that the outputexcel.csv file will be saved to the same place (including headers).

  • Using wildcards for String compare

    Hello,
    I want my prog to find out all Strings which start with the letters 'File'. How can I make a String compare by using wildcards ?
    Thanx,
    Findus

    You may use the String method startsWith to find strings beginning with File. eg. filename.startsWith("File")
    for more complicated comparisons you might want to use regular expressions.

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • How to Communicate a string between LabView 7.0 and VB using TCP/IP

    HI
    I want to know how to communicate , " by passing a string  "  between LabView 7.1  and VB 6.0  using tcp/ip . Please if anyone couild help me on this..
    Regards
    Ashish Doshi

    Ashish,
    I've got great news for you! LabVIEW has built in TCP functions. They are located in Data Communication>>Protocols>>TCP. From the LabVIEW side, I think you'll find everything you need in there. Good luck!
    Chris C
    Chris Cilino
    National Instruments
    LabVIEW Product Marketing Manager
    Certified LabVIEW Architect

  • Problems with string comparing

    I have a function, getPlayerName() that returns the contents of a text field, but i want the dialog box to check and see if there was anything typed in there, so i have done things like if(this.getPlayerName() != null), if(this.getPlayerName() != "") and if(this.getPlayerName() != " "), and the statement still lets it go by when i dont type anything in. is there something else i'm suppose to do?

    When comparing strings (and any other object for that matter) you must use the equals method. In your case you should probably also trim the string for whitespace before comparing:
    if(!this.getPlayerName().trim().equals("")) In this case you can also use the length method:
    if(this.getPlayerName().trim().length() != 0)

  • Difference between .equals("") and .equals(null)

    Can any one please tell me the difference between the following?
    String someString;
    someString = someMethod(someParameter);
    After the method call, if I am going for a check like this..
    what will each check do?
    1. if (someThing.equals(null))
    2. if (someThing.equals(""))
    3. if (something == null )
    4. if (something == "" )
    Thanks in advance,
    Regards
    Rakesh

    First, understand that the empty string ("") and null are two very different things. The empty string ("") is a string object that just doesn't contain any characters. It's still an object though--you can call it's methods.
    Null, on the other hand, is essentailly nothing. It's a special value that means "Nothing. No object here." (Ignoring for now the distinction among the null type, a null reference, etc.) You can't call methods or refer to fields on null. If you try, you'll get a NullPointerException.
    1. if (someThing.equals(null))Calls the equals method on someThing to compare someThing to null. If someThing is not null, this returns false. If someThing is null it... what? returns true? Nope. Throws NullPointerException. You can't call the equals method on a null someThing.
    Therefore there's no point in ever using equals(null).
    2. if (someThing.equals(""))Calls the equals method on someThing to compare someThing to the empty string (""). If someThing is not null, but is empty, it returns true. If someThing is non-null and is not empty (e.g., "abc"), it returns false. If someThing is null, it throws NPE.
    One generally uses the equals method, not the == operator to compare objects--that is, to see if their contents or states are equal. The == operator is used to see if two referecnes refer to the same object, or if a reference is null.
    3. if (something == null ) Evaluates to true if something is null and to false if something is non-null. Never throws NPE (since we're not calling a method or accessing a field).
    4. if (something == "" ) You never really want to use == to compare a String variable to a String literal like this. This checks to see if the reference something is referring to the same object as the "" is. The "" will be referring to an object in the constant pool. Even if something is the empty string, it may not refer to the same entry in the constant pool.
    That is (something == "") could evaluate to false, but something.equals("") could return true.

  • A Universal Comparator using reflections

    Folks,
    <edit purpose="bump" secondaryPurpose="explain stuff a bit better">
    Sorry I didn't explain what this thing is... and zero bites in the veiw of several active silver backs means, I presume, that I did something magorly wrong... so...
    This class class calls the compare method passing the result of named "getter" method on the two objects to compare. So what? Well... Ummm... It means you can sort by any field of any List (or PriorityQueue, or what-have-you) without having to pre-write a Comparator.... Which is good.
    </edit>
    I was inspired by a blog entry by ?was it warnerja? which was referenced in a thread which was linked from an off-topic post in a thread I read last ?Thursday? night... and to cut a long storry short... I can't find the blog entry again :(
    My implementation is based on [this one by Lone Deranger|http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3308&lngWId=2] ... which has a couple of problems
    1. infinite recursion in the equals method == OutOfStackSpaceException
    2. It gets the method defintion every time you call compare == sloooooooooooowwwwwwwwwww.
    This version
    * is a bit faster
    * verifies as much as possible in constructor.
    * uses generics to verify (as far as possible) the runtime "compared Class" type.
    But I'm pretty sure someone who really knows there generics could improve upon the implementation (or quit possibly the fundamental design). Specifically I'm not in love passing the Class of the compared objects as well as define the generic type. There's GOT to be a better way... I'm just to inexpert/stupid to recognise it... I've probably been staring straight at it for the last two hours.
    So.... This thing works... but any suggestions and/or constructive criticism would be welcome ;-) Thanx.
    UniversalReflectiveComparator.java
    package forums;
    import java.util.Comparator;
    import java.lang.reflect.Method;
    import java.lang.reflect.Type;
    public class UniversalReflectiveComparator<T> implements Comparator<T>
      public static String DEFAULT_METHOD_NAME = "toString";
      public static final int ASCENDING = 1;
      public static final int DESCENDING = -1;
      public static int DEFAULT_ORDER = ASCENDING;
      private static final java.lang.Object[] NO_ARGS = null;
      private final String methodName;
      private final Method getterMethod;
      private final int order;
      public UniversalReflectiveComparator(Class classToCompare)
        throws NoSuchMethodException
        this(classToCompare, DEFAULT_METHOD_NAME, DEFAULT_ORDER);
      public UniversalReflectiveComparator(Class classToCompare, String methodName)
        throws NoSuchMethodException
        this(classToCompare, methodName, DEFAULT_ORDER);
      public UniversalReflectiveComparator(Class classToCompare, int order)
        throws NoSuchMethodException
        this(classToCompare, DEFAULT_METHOD_NAME, order);
      @SuppressWarnings("unchecked")
      public UniversalReflectiveComparator(Class classToCompare, String methodName, int order)
        throws NoSuchMethodException
        getterMethod = classToCompare.getMethod(methodName, (java.lang.Class<?>[])null);
        Class returnType = getterMethod.getReturnType();
        if ("void".equals(returnType.getName())) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method"
          + " because its return type is void (ie: it does not return a value to compare).");
        if ( !doesImplement(returnType, Comparable.class.getCanonicalName()) ) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method"
          + " because its return type '"+returnType.getName()+"' does not implement Comparable.");
        this.methodName = methodName;
        this.order = order;
      @Override
      @SuppressWarnings("unchecked")
      public int compare(T o1, T o2) {
        try {
          Comparable o1attribute = (Comparable) getterMethod.invoke(o1, NO_ARGS);
          Comparable o2attribute = (Comparable) getterMethod.invoke(o2, NO_ARGS);
          return o1attribute.compareTo(o2attribute) * order;
        } catch (Exception e) {
          throw new IllegalStateException("Failed to compare "+clazz(o1)+ " to "+clazz(o2), e);
       * Returns the type and string value of the given object.
       * eg: java.lang.String 'Hello World!'
      private static String clazz(Object object) {
        return object.getClass().getCanonicalName()+" '"+String.valueOf(object)+"'";
       * Returns: Does the given clazz implement the given interfaceName
       * @param clazz the Class to be examined.
       * @param canonicalInterfaceName the full name (with or without generics)
       *  of the interface sought: path.to.Interface[<path.to.GenericType>]
      private static boolean doesImplement(Class clazz, String canonicalInterfaceName) {
        for ( Type intrface : clazz.getGenericInterfaces() ) {
          if ( intrface.toString().startsWith(canonicalInterfaceName) ) {
            return true;
        return false;
    UniversalComparatorTest.java
    package forums;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    // A simple "Bean" class for testing only.
    // Does NOT implement comparable!
    class Word {
      private final String word;
      public Word(String word) { this.word=word; }
      public String getWord() {  return this.word; }
      public void noop() { }
      public String toString() { return this.word;  }
      public Word notComparable() { return new Word("notComparable"); }
    class UniversalComparatorTest
      @SuppressWarnings("unchecked")
      public static void main(String[] args) {
        try {
          List<Word> words = readWords("WordFinder.txt");
          System.err.println("---------------------------------------------------");
          // SUCCESS CASES
                           //short for new UniversalReflectiveComparator<Word>(Word.class,"toString",ASCENDING);
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class));
            System.out.println(words);
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "getWord", UniversalReflectiveComparator.DESCENDING));
          } catch (Exception e) {e.printStackTrace();}
          System.out.println(words);
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, UniversalReflectiveComparator.DESCENDING));
          } catch (Exception e) {e.printStackTrace();}
          System.out.println(words);
          System.err.println("---------------------------------------------------");
          // FAIL CASES
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "nonExistantMethodName"));
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "noop"));
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "notComparable"));
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
        } catch (Exception e) {
          e.printStackTrace();
       * reads each line of the given file into a List of strings.
       * @param String filename - the name of the file to read
       * @return an List handle ArrayList of strings containing file contents.
      public static List<Word> readWords(String filename) throws FileNotFoundException, IOException {
        List<Word> results = new ArrayList<Word>();
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(filename));
          String line = null;
          while ( (line=reader.readLine()) != null ) {
            results.add(new Word(line));
        } finally {
          if(reader!=null)reader.close();
        return results;
    }Cheers all. Keith.
    PS: If you happen to know that blog entry... could you post a link... please.
    Edited by: corlettk on 2/11/2008 15:52 - Ooops!
    Edited by: corlettk on 2/11/2008 18:20 - You Snobs!
    Edited by: corlettk on 2/11/2008 19:00 - Dodgems bump!

    Here's the latest installment...
    This thing writes, compiles and instantiates and caches the requested implementation of Comparator<?> on-the-fly with the system default javax.tools.JavaCompiler
    Some Notes:
    * Gee, it's just sooooo easy to invoke the compiler.
    * Compilation errors are printed to stdout.
    * It takes too long to compile... aprox nine-tenths of a second (0.95 +/- 0.04) for a really simple little class.
    * I like the cache... subsequent calls for the same comparator are instant ;-)
    * Possible enhancement: oninit: load the cache with .class's from the specified package (a seperate comparators package), so you only have to create each comparator once per release (ie: like JSP's)
    * It throws too many distinct exception types... I think it would be better if it threw only one ComparatorGenerationException (but I'm too lazy to fix it now).
    * I don't like the "staticness" anymore, especially with a cache involved. Maybe a ComparatorFactoryConfig extends Properties would be the best way to configure the factory? Or maybe a ComparatorSpec class should be passed to the createComparator method... to eliminate all that cumbersome overloading to just to provide defaults. Hmmm.
    * The order switch means you can sort both ways using the one generated
    * A simillar "nulls first or last" switch would be a good enhancement.
    * Camickr's solution also features a case[in]senstive switch... feel free to add it ;-)
    * It's still not a scratch on Mr Kirkman's ASM solution (which is aprox 10 times as fast), but it'll definately give the "pure reflection" solution a run for it's money.
    * I can imagine a common "front end" for both the "reflective" and "code-gen" solutions... if the list size is less than 10,000 just reflect it, else code-gen.
    UniversalOnTheFlyCompiledComparatorFactory.java
    package forums;
    import java.util.Comparator;
    import java.lang.reflect.Method;
    import java.lang.reflect.Type;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Map;
    import java.util.HashMap;
    import javax.tools.DiagnosticCollector;
    import javax.tools.JavaCompiler;
    import javax.tools.JavaFileObject;
    import javax.tools.StandardJavaFileManager;
    import javax.tools.ToolProvider;
    public class UniversalOnTheFlyCompiledComparatorFactory
      public static String DEFAULT_METHOD_NAME = "toString";
      public static String SRC_DIR = "C:/java/home/src/";
      public static String PACKAGE = "forums";
      public static final int DESCENDING = -1;
      public static final int ASCENDING = 1;
      public static int DEFAULT_ORDER = ASCENDING;
      private static final java.lang.Class<?>[] NULL_CLASS_ARRAY = null;
      public static Comparator createComparator(Class classToCompare)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        return createComparator(classToCompare, DEFAULT_METHOD_NAME, DEFAULT_ORDER);
      public static Comparator createComparator(Class classToCompare, String methodName)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        return createComparator(classToCompare, methodName, DEFAULT_ORDER);
      public static Comparator createComparator(Class classToCompare, int order)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        return createComparator(classToCompare, DEFAULT_METHOD_NAME, order);
      public static Map<String,Comparator<?>> cache = new HashMap<String,Comparator<?>>();
      @SuppressWarnings("unchecked")
      public static Comparator createComparator(Class classToCompare, String methodName, int order)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        final String key = classToCompare.getName()+"."+methodName+"_"+order;
        Comparator<?> comparator = cache.get(key);
        if (comparator != null) {
          return comparator;
        final Method getterMethod = classToCompare.getMethod(methodName, NULL_CLASS_ARRAY);
        final Class returnType = getterMethod.getReturnType();
        if ("void".equals(returnType.getName())) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method because its return type is void (ie: it does not return a value to compare).");
        if ( !isComparable(returnType) ) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method because its return type '"+returnType.getName()+"' does not implement Comparable.");
        final File javaFile = writeComparatorJava(classToCompare, getterMethod, order);
        if ( ToolProvider.getSystemJavaCompiler().run(null, System.out, System.err, javaFile.getName()) != 0 ) {
          throw new CompilationException("Failed to compile comparator file: "+javaFile.getAbsolutePath());
        final String comparatorClassName = PACKAGE+"."+javaFile.getName().replaceAll("\\.java$", "");
        comparator = (Comparator<?>) Class.forName(comparatorClassName).newInstance();
        cache.put(key, comparator);
        return comparator;
      private static File writeComparatorJava(Class classToCompare, Method getterMethod, int order)
        throws IOException, CompilationException
        final String nameOfClassToCompare = classToCompare.getName().replaceAll("^.*(?=\\.)\\.",""); // remove everything before the last .
        final String getterMethodName = getterMethod.getName();
        final String comparatorClassName = nameOfClassToCompare + getterMethodName.replaceAll("^get","").replaceAll("toString","String") + "Comparator";
        final File comparatorClassFile = new File(SRC_DIR+PACKAGE+"/"+comparatorClassName+".java");
        PrintWriter out = null;
        try {
          out = new PrintWriter(new FileWriter(comparatorClassFile));
          out.println("package "+PACKAGE+";");
          out.println("public class "+comparatorClassName+" implements java.util.Comparator<"+nameOfClassToCompare+">");
          out.println("{");
          out.println("  public static final int DESCENDING = -1;");
          out.println("  public static final int ASCENDING = 1;");
          out.println("  public static final int DEFAULT_ORDER = "+order+";");
          out.println("  public final int order;");
          out.println();
          out.println("  public "+comparatorClassName+"() { this(DEFAULT_ORDER); }");
          out.println();
          out.println("  public "+comparatorClassName+"(int order) { this.order = order; }");
          out.println();
          out.println("  // nulls come last");
          out.println("  public int compare("+nameOfClassToCompare+" a, "+nameOfClassToCompare+" b) {");
          out.println("    if (a==null) {");
          out.println("      return b==null ? 0 : -1;");
          out.println("    } else {");
          out.println("      return b==null ? 1 : a."+getterMethodName+"().compareTo(b."+getterMethodName+"()) * order;");
          out.println("    }");
          out.println("  }");
          out.println();
          out.println("}");
        } finally {
          if (out!=null)out.close();
        return comparatorClassFile;
       * Returns: Does the given clazz implement the given interfaceName
       * @param clazz the Class to be examined.
       * @param canonicalInterfaceName the full name (with or without generics)
       *  of the interface sought: path.to.Interface[<path.to.GenericType>]
      private static boolean isComparable(Class clazz) {
        for ( Type i : clazz.getGenericInterfaces() ) {
          if ( i.toString().startsWith("java.lang.Comparable") ) {
            return true;
        return false;
    UniversalComparatorTest.java
    package forums;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    // A simple "Bean" class for testing only.
    // Does NOT implement comparable!
    class Word {
      private final String word;
      public Word(String word) { this.word=word; }
      public String getWord() {  return this.word; }
      public void noop() { }
      public String toString() { return this.word;  }
      public Word notComparable() { return new Word("notComparable"); }
    class UniversalComparatorTest
      @SuppressWarnings("unchecked")
      public static void main(String[] args) {
        try {
          List<Word> words = readWords("WordFinder.txt");
          System.err.println("---------------------------------------------------");
            long start = System.nanoTime();
            try {
              Comparator<Word> wordComparator = UniversalOnTheFlyCompiledComparatorFactory.createComparator(Word.class);
              Collections.sort(words, wordComparator);
              System.out.println(words);
            } catch (Exception e) {e.printStackTrace();}
            long stop = System.nanoTime();
            System.err.printf("took %6.4f seconds%n", (stop-start)/1000000000.0);
            System.err.println("---------------------------------------------------\n");
            long start = System.nanoTime();
            try {
              Comparator<Word> wordComparator = UniversalOnTheFlyCompiledComparatorFactory.createComparator(Word.class);
              Collections.sort(words, wordComparator);
              System.out.println(words);
            } catch (Exception e) {e.printStackTrace();}
            long stop = System.nanoTime();
            System.err.printf("took %6.4f seconds%n", (stop-start)/1000000000.0);
            System.err.println("---------------------------------------------------\n");
        } catch (Exception e) {
          e.printStackTrace();
       * reads each line of the given file into a List of strings.
       * @param String filename - the name of the file to read
       * @return an List handle ArrayList of strings containing file contents.
      public static List<Word> readWords(String filename) throws FileNotFoundException, IOException {
        List<Word> results = new ArrayList<Word>();
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(filename));
          String line = null;
          while ( (line=reader.readLine()) != null ) {
            results.add(new Word(line));
        } finally {
          if(reader!=null)reader.close();
        return results;
    }Cheers. Keith.
    It's Bed Time ;-)

  • RichEditableText: export().equals() and HTML export

    1. How can I find out that two richEditableText.export() are equal?
    At least the order of the attributes in the TextFlow element is random which means that exported strings cannot be compared directly. Take for example the trunk.mxml from http://bugs.adobe.com/jira/browse/SDK-21836 and compile+run it several times and you see the different order of attributes. Is there a utility method somewhere to compare two exports? (BTW releasing the source of TLF would ease these kind of bug hunting...)
    I know how to use richEditableText.textFlow.generation but this only indicates changes in the current component.
    2. Is supporting html import/export on the roadmap?
    (This question got burried in the information stream... http://forums.adobe.com/message/2042067#2042067)
    Gordon Smith: TLF's TextFilter class supports importers and exporters for HTML_FORMAT, but I haven't tried them and don't know how robust they are.
    I think the HTML export in TLF is not yet stable. The thing is that once
    it is stable there is pretty much no way to insert the import
    functionality into RichEditableText without rewriting most of the
    component. In my opinion, it should be either integrated into
    RichEditableText even at this early stage or RichEditableText should be
    refactored to allow extending it in an easier way.
    Thanks for any hints,
    Marc

    Hi Abhishek,
    Nice conversation I do not expect that TLF covers the full HTML standard. After all, browsers are too good when it comes to HTML rendering...
    with varying degrees of fidelity.
    I remember reading in the TLF forum, that HTML import/export was experimental. That's why I wrote that HTML is not ready for prime time. Also your comment shows that HTML is a poor choice from a Flex perspective. Unfortunately, it's unclear what varying degrees of fidelity really means as I'm not aware of any precise documentation or code.
    Concerning your idea about passing around a (mutable) instance of TextFlow, I'm not a great fan. The power of markup is besides others, that it is a comparable description of content and format. So I definitely prefer an equal function. If this function doesn't make it into the Flex 4 release, I  reluctantly add to each TLF markup a dirty flag which is based on TextFlow.generation.
    As mentioned before, I prefer TLF could export all content and formatting into HTML compliant format. There are many reasons why HTML is a huge benefit over any new, widely undocumented format (this is not specific to TLF or FXG). A few reasons that come to my mind:
    - Server side: Apache Lucene has a battle-proof extractor. With TLF or FXG, I had to write and configure my own.
    - Server side: Extract and modify links in content. This is obviously very easy with HTML as there are age-old libs available.
    - Flash Player: Compare two TLF markups. There might be also no actionscript lib for HTML available. But I'd happily start a project for HTML but not for a new format without underlining code and thorough doc.
    - HTTP communication: what's the mime type of TLF or FXG?
    - Every developer knows HTML, TLF/FXG must be learned. I regard this learning as a high barrier as TLF does not seem to be a big step forward compared to HTML.
    Note that I don't prefer HTML because it is an "open standard". It's because the whole world knows HTML and that brings a much higher engineering efficiency (and that's maybe due to the open standard). If not all information of TLF can be export HTML, it's a pity but just document it.
    Looking forward to your thoughts/comments,
    Marc
    abhishek.g wrote: Hi Marc,
    Thanks for your reply.
    TLF supports many different markup formats (TLF, FXG, Plain text, HTML) with varying degrees of fidelity. It would simply not do to compare HTML because there isn't a 1:1 correspondence between TLF and HTML capabilities. From that perspective, TLF format would be your best bet though I realize there is the problem of inconsistent attribute order.
    Perhaps your scenario is better addressed by having utilities to compare TextFlow instances rather than comparing corresponding markup (this needs additional thought).
    As for HTML import/export, it is obviously be beyond TLF's scope to implement the full HTML standard. The current implementation is loosely based on the HTML capabilities of flash.text.TextField (see htmlText property), which itself is a small subset of the standard, and deviates from it in some ways. When you say HTML support is not ready for prime time, are you referring to this limited scope, or have you encountered specific bugs in the implementation? If the former, I'd like to know what your expectations are. If the latter, please report them.
    Thanks
    Abhishek
    (Adobe Systems Inc.)
    This message was sent to: faindu
    To post a reply to the thread message, either reply to this email or visit the message page:
    http://forums.adobe.com/message/2059470#2059470
    --end--
    mail transfer stalled...

Maybe you are looking for

  • How to install Cisco Work 3.2 on Windows 2008 Server Standard R2

    Hi Everyone, I have got Cisco Works LAN Management 3.2. But the problem is that i have a Windows 2008 Server Standard R2 and when i try to install, it fails. What I read from the below link is that it supports "Windows 2008 Server Standard and Enterp

  • Data Integrator and Data Quality

    Hi, I worked on BI 7.0 and now exploring Business objects. I wanted to know how Data Integrator and Data Quality products relate to SAP BI 7. What is the purpose of using them. Is this integration and quality features not embedded in SAP BI 7.

  • Problems with the testing of querys in view objects

    I am working whih view object and i like to do one query with parameters for it(all with the wizard). The help of wizard no help me, because i write the clause where similar to the clause of the help. the error is: ORA-00904 Exception:java.jql.SQLExc

  • How do I set up my 'author' page on iBooks?

    Can anyone tell me how to set up my 'author' page on iBooks?  I have three books, one from a major publisher, two from an independent, plus an audio program all listed, but no author page for any of them.  I'd like to connect them all together to a s

  • Exporting stills in 16.9 ratio

    I'm exporting a lot of stills from a project in FCP with an aspect ratio of 16.9, they are coming out in a squeezed 4.3 look, how do I export them and maintain the 16.9 look?? Catherine Bennett