Utility comparable to dcmnctl in 10.1.3

In 10.1.2 we used the following commands when our instances were caching the configuration files and we needed to re-sync them
./dcmctl shell
resyncInstance
resetfiletransaction
and others.
In Oracle 10.1.3 we do not have dcmctl. What is the comparable commands in opmnctl. I have read the documentation and I am unable to find any.
Does anyone know how these functions are provided in 10.1.3

That approach seems good, however lots of changes when you deal with HW, adapters in 10.1.3.x
AFAIK, 10.1.2.x is deprecated and all customers have moved seamlessly to 10.1.3.x, you would get support for 10.1.2.0.2, but no new patches/bugs will be fixed.

Similar Messages

  • 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 ;-)

  • How do I accept/reject green/red changes in a FM CMP Compare Document

    I am working in FM 11 and needed to merge one file that two writers worked on at the same time with different sections of that file updated. I used the FM Utility > Compare Documents. The result CMP file showed me the inserted text in bright green and the deleted text in red. How do you accept/reject these changes? My workaround is to retype what I wanted to keep and select and delete text I wanted to delete.
    I also tried to use SVN update to merge the files, but SVN didn't seem to be able to merge my two files (even though SVN merged a text file that user 1 UPDATED before they COMMITTED their change. The UPDATE merged the changes from writer 1 to the working copy from writer 2 without disturbing writer 2's changes. Then writer 2 was able to COMMIT. But this only worked on a TXT file and did not work with FM files. With FM, SVN just would not let writer 2 UPDATE if his copy was not in sync with the committed copy.
    Ideally I would like to be able to merge changes on the same file from two writers who updated different sections. Any suggestions? Thanks.

    Another approach:
    FrameMaker uses the conditions Inserted and Deleted to mark inserted and deleted text in the CMP file.
    In the Search/Replace dialog select the Deleted condition for deleted text to search for.
    Leave the Replace box empty.
    Then search for the Deleted condition and either replace (i.e. delete the text) or leave it as it is.
    After this search/replace the remaining text with the Deleted condition is correct. Therefore delete this condition without deleting the text.
    Then do the same with the Inserted condition for inserted text. Either delete this text or leave it as it is.
    Then delete this Inserted condition.

  • How to compare the values stored in the list

    Hi,
    I am having the requirement that i want to compare the values stored in the list.How to store the values in the list and compare the list values stored inside it.
    Regards,
    Ahamad

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List)
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html

  • Question on import java.util.ArrayList, etc.

    Hi,
    I was wondering what the following meant and what the differences were. When would I have to use these:
    import java.util.ArrayList;
    import java.util.Collections; <--I especially don't understand what this means
    import java.util.Comparator; <---same for this (can I consolidate these into the bottom two?)
    import java.io.*;
    import java.util.*;

    MAresJonson wrote:
    Also, what does this mean:
    return foo == f.getFoo() ? true : false;
    (more specifically...what does the "? true : false" mean and is there another way to code that?)It's called the ternary operator. For your specific example, you could just do:
    return foo == f.getFoo();But, more generally,
      return foo == f.getFoo() ? "equal" : "Not equal";means:
    if (foo == f.getFoo()) {
       return "equal";
    else {
       return "Not equal";
    }As everyone else said at the same time...

  • ClassCastException when querying an entry set w/ Comparator

    Hi,
    I have come across a problem trying to retrieve a sorted entry set from a distributed cache. I have a cache containing objects of a single class (OrderHistory) and am using the NamedCache.entrySet(filter, comparator) method. The results are fine when only a filter is used, and also when 'null' is passed as the comparator (correctly sorting OrderHistories in natural order). However, a ClassCastException occurs when I specify my own OrderSorter as a comparator. This occurs even when the OrderSorter class is stripped of all mention of the OrderHistory class and the compare method is reduced to:
         public int compare(Object o1, Object o2) {
              return 1;
    OrderSorted implements both Comparator and ExternalizableLite. It appears that Tangosol is attempting to perform the cast internally. The stack trace is as follows:
    Failed request execution for DistributedCache service on Member(Id=1, Timestamp=2007-05-14 15:19:34.9, Address=10.142.194.36:8088, MachineId=17956))
    java.lang.ClassCastException: com.[...].OrderHistory
         at com.tangosol.util.comparator.EntryComparator.compare(EntryComparator.java:103)
         at com.tangosol.util.comparator.SafeComparator.compareEntries(SafeComparator.java:106)
         at com.tangosol.util.comparator.EntryComparator.compare(EntryComparator.java:114)
         at java.util.Arrays.mergeSort(Arrays.java:1284)
         at java.util.Arrays.sort(Arrays.java:1223)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache$Storage.extractBinaryEntries(DistributedCache.CDB:9)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache$Storage.query(DistributedCache.CDB:209)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache.onQueryRequest(DistributedCache.CDB:23)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache$QueryRequest.run(DistributedCache.CDB:1)
         at com.tangosol.coherence.component.net.message.requestMessage.DistributedCacheRequest.onReceived(DistributedCacheRequest.CDB:12)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.Service.onMessage(Service.CDB:9)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.Service.onNotify(Service.CDB:122)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache.onNotify(DistributedCache.CDB:3)
         at com.tangosol.coherence.component.util.Daemon.run(Daemon.CDB:35)
         at java.lang.Thread.run(Thread.java:595)
    Any ideas?
    Thanks in advance,
    James

    Err, seems that bug is not fixed yet, at least version 3.5/459 still has it. Too bad.
    Here is my test case & stack trace:
    log("building cache instance");
    NamedCache cache = CacheFactory.getCache("mycache");
    log("put some objects into the cache");
    cache.put("#TEST#10#001","#1111");
    cache.put("#TEST#10#012","#2222");
    cache.put("#TEST#10#003","#3333");
    cache.put("#TEST#20#1","#4444");
    log("building filter object");
    Filter filter = new LikeFilter(new KeyExtractor(), "#TEST#10%",'\\',true);
    testComparator comparator = new testComparator();
    for (Iterator it = cache.entrySet(filter,new EntryComparator(comparator, EntryComparator.CMP_KEY)).iterator(); it.hasNext();) {
    Map.Entry curr_entry = (Map.Entry)it.next();
    System.out.println("curr_key="+curr_entry.getKey().toString()+
    "curr_value="+curr_entry.getValue().toString()
    Exception in thread "main" java.lang.ClassCastException: java.lang.String
         at com.tangosol.util.comparator.EntryComparator.compare(EntryComparator.java:99)
         at com.tangosol.util.comparator.SafeComparator.compareSafe(SafeComparator.java:166)
         at com.tangosol.util.comparator.SafeComparator.compare(SafeComparator.java:84)
         at com.tangosol.util.comparator.EntryComparator.compare(EntryComparator.java:115)
         at java.util.Arrays.mergeSort(Arrays.java:1284)
         at java.util.Arrays.sort(Arrays.java:1223)
         at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.DistributedCache$ViewMap.entrySet(DistributedCache.CDB:105)
         at com.tangosol.coherence.component.util.SafeNamedCache.entrySet(SafeNamedCache.CDB:1)
    -------------------------------------

  • Comparator for different classes

    I have a crazy need to be able to hold a few hundred thousand objects in a Set. These objects can vary from Integers, Doubles to Strings. Normally it seems a HashSet would be the perfect implementation for this, however, this Set is built once and searched through several million times. So it makes sense to have a SortedSet available for this to improve search times. Having different sets for each Class type is not an option.
    I've come up with this code, which works fairly well as far as I can tell, but would like your general opinions on how it can be improved. I can't find a failing point, yet, and would like the eyes of many to tell me that I'm wrong - and that it can fail somehow.
    public class DifferentObjectComparator implements Comparator, Serializable
         public int compare(Object o1, Object o2)
              if (o1 == null && o2 == null) return 0;
              if (o1 == null && o2 != null) return 1;
              if (o1 != null && o2 == null) return -1;
              if (o1.getClass() == o2.getClass())
                   return ((Comparable) o1).compareTo(o2);
              if (o1 instanceof Number && o2 instanceof Number)
                   double retVal = ((Number) o1).doubleValue() - ((Number) o2).doubleValue();
                   if (retVal < 0) return -1;
                   if (retVal > 0) return 1;
                   return 0;
              return -1;
    }If you know of and/or can think of a better way to do this, please tell. Keep in mind it must use a SortedSet implementation.

    cvweiss__ wrote:
    After a couple of tweaks and some extensive testing I am now satisfied that the following code fully complies with the specifications given in the javadoc for java.util.Comparator. I'm posting this here for those in the future who have this requirement.
    public class DifferentObjectComparator implements Comparator, Serializable
         public int compare(Object o1, Object o2)
              if (o1 == o2) return 0; // good for two nulls or exact same Object
              if (o1 == null && o2 != null) return 1;
              if (o1 != null && o2 == null) return -1;
              if (o1.getClass() == o2.getClass())
                   return ((Comparable) o1).compareTo(o2);
              if (o1 instanceof Number && o2 instanceof Number)
                   double retVal = ((Number) o1).doubleValue() - ((Number) o2).doubleValue();
                   if (retVal < 0) return -1;
                   if (retVal > 0) return 1;
                   return 0;
              return o1.getClass().getName().compareTo(o2.getClass().getName());
    if they ALL implements Comparable, wouldn't the Set be
    Set<? extends Comparable> theSet;? In which case, the Comparator could be more elegantly written using similar generics, like
    public class MyComparator implements Comparator<Comparable> {
      public int compare(Comparable c1, Comparable c2) {
                  if (c1 == c2) return 0;
              if (c1 == null && c2 != null) return 1;
              if (c1 != null && c2 == null) return -1;
              if (c1.getClass() == c2.getClass())
                   return c1.compareTo(c2);
              if (c1 instanceof Number && c2 instanceof Number)
                   double retVal = ((Number) c1).doubleValue() - ((Number) c2).doubleValue();
                   if (retVal < 0) return -1;
                   if (retVal > 0) return 1;
                   return 0;
              return c1.getClass().getName().compareTo(c2.getClass().getName());   // looks weird to me
    }no more ugly castings! (well, except for casting to Number, but that's inherent to the weird spec to begin with)

  • Java.util.Arrays.sort for Vector

    I used the java.util.Arrays.sort to sort an array based on the method below.
                  java.util.Arrays.sort(array, 0, total, new ComparatorX());
               repaint();
                class ComparatorX implements java.util.Comparator
              public int compare( Object p1, Object p2){
                   int x1=((Point)p1).x;
                   int x2=((Point)p2).x;
                   if(x1>x2)
                                return 1;
                   if(x1>x2)
                                return -1;
                   return 0;
         }I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.

    BTW: Don't know if it's just a typing mistake, but your code contains an error:
    class ComparatorX implements java.util.Comparator     {
       public int compare( Object p1, Object p2) {
          int x1=((Point)p1).x;
          int x2=((Point)p2).x;
          if (x1>x2) {
             return 1;
          if (x1>x2) {  // Should be: if (x2 > x1) ...
             return -1;
          return 0;

  • How to Compare Lists of Objects

    Hello All,
    I have two lists(self developed; not using Java's inherent list functionality) containing objects of the same class. Now I would like to compare the elements within the lists one on one.
    Meaning, I would like to compare the two lists to see whether they contain identical elements or not.
    How should I do this.
    Please help !!
    Thank you.

    If there is an implicit order on your objects then
    1.) Write a Comparator for your objects
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html
    2.) Sort both lists
    3.) int j = 0;
    FOR EACH item IN list1 DO
      WHILE list2.get(j) IS LESS THAN item DO
        ++j;
      OD
      IF item EQUALS list2.get(j) THEN
        PRINT "Found dups " + item + " and " + list2.get(j)
      FI
    ODIf there exists no implicit ordering, you can only use the trivial solution:FOR EACH item1 IN list1 DO
      FOR EACH item2 IN list2 DO
        IF item1 EQUALS item2 THEN
          PRINT "Found dups " + item1 + " and " + item2
        FI
      OD
    OD(BTW - this is pseudo-code)
    ... or put you stuff in to Sets and use retainAll ...

  • Sorting with Comparator, wrong order?

    Hello,
    i've a string array, and every string in this array in form of "Firstname [MiddleName] LastName". After i sort the array i get "List A" below, but i expect to get "List B". All "Alp"s must be together like dictionary order, isn't it? What cause this?
    Regards,
    List A:
    Alp BBBBB
    Alper KKKKK
    Alper SSSSSS
    Alp KKKKKKK
    Alp OOOO
    Alp ÖÖÖÖÖÖÖÖÖ
    Alptu&#287; VVVVV
    Alp YYYYY KKKKK
    Alp YYYYYYYYYY
    List B
    Alp BBBBB
    Alp KKKKKKK
    Alp OOOO
    Alp ÖÖÖÖÖÖÖÖÖ
    Alp YYYYY KKKKK
    Alp YYYYYYYYYY
    Alper KKKKK
    Alper SSSSSS
    Alptu&#287; VVVVV
    Code
    import java.text.Collator;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Locale;
    public class sort {
        static final Comparator<String> x = new Comparator<String>() {
            public int compare(String o1, String o2) {
                return Collator.getInstance(new Locale("tr", "TR")).compare(o1, o2);
        public static void main(String[] args) {
            String[] snames={
                     "Alp BBBBB",
                     "Alper KKKKK",
                     "Alper SSSSSS",
                     "Alp KKKKKKK",
                     "Alp OOOO",
                     "Alp ÖÖÖÖÖÖÖÖÖ",
                     "Alptu&#287; VVVVV",
                     "Alp YYYYY KKKKK",
                     "Alp YYYYYYYYYY"};
            List lsnames=Arrays.asList(snames);
            Collections.sort(lsnames, x);
            System.out.println(lsnames.toString().replaceAll(",", "\n"));
    }

    static final Comparator<String> x = new Comparator<String>()
            final private Collator collator = Collator.getInstance(new Locale("tr", "TR"));
            final private Pattern splitterPattern = Pattern.compile("\\s+");
            public int compare(String o1, String o2)
                try
                    final String[] fields1 = splitterPattern.split(o1, 2);
                    final String[] fields2 = splitterPattern.split(o2, 2);
                    for (int i = 0; i < 2; i++)
                        final int v = collator.compare(fields1, fields2[i]);
    if (v != 0)
    return v;
    } catch (Exception e)
    // Possibly nothing to do here but, depending on how
    // fatal one views it, one could throw
    // an unchecked exception, just print a stack
    // trace or totally ignore the exception.
    // Since this is probably a system error, my
    // preference is for
    throw new Error("Problem in comparator", e);
    return -1;
    public static void main(String[] args)
    String[] snames =
    "Alp BBBBB",
    "Alper KKKKK",
    "Alper SSSSSS",
    "Alp KKKKKKK",
    "Alp OOOO",
    "Alp ÖÖÖÖÖÖÖÖÖ",
    "Alptu&#287; VVVVV",
    "Alp YYYYY KKKKK",
    "Alp YYYYYYYYYY"
    List<String> lsnames = Arrays.asList(snames);
    Collections.sort(lsnames, x);
    System.out.println(lsnames.toString().replaceAll(",", "\n"));
    }Edited by: sabre150 on Jan 6, 2009 10:37 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Sorting in servlet without a Comparator???

    Hello Guys,
    I am trying to sort here.
    I have the following snippet in the servlet:
    List l = Arrays.asList(recipient);
    Object[] ol = l.toArray();
    Arrays.sort(ol);          
    Now I wanna set the ol object array. The following sets it. But the thing is not sorted.
    request.getSession().setAttribute("recipients", ol);
    Your ideas(easiest) are appreciated.
    Thanks.

    To start, your problem has completely nothing to do with servlets. You don't have a problem with javax.servlet API, but with java.util API (java.util.List, java.util.Arrays and java.util.Comparator). You would get the very same problem if you just run the code as a plain vanilla Java application in command console.
    Regarding to your problem: to sort objects you need a Comparator or the objects needs to implement Comparable. Learn more here: [http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html]. If you stucks, please continue at 'New to Java' forum.

  • Chinese Charactor sorting in List using Comparator and Collator

    I've used Collator.sort method with Locale.TRADITIONAL_CHINESE Locale to sort an ArrayList which contains a list of Chinese charactor. But it seems that the ordering is not based on stroke.
    Here is the coding for compare methods whose class implements java.util.Comparator
         public int compare(Object obj1, Object obj2){
              String string1 = (String)obj1;
              String string2 = (String)obj2;
              int compareResult = 0;
              Locale locale = locale = Locale.TRADITIONAL_CHINESE;
              Collator collator = Collator.getInstance(locale);
              compareResult = collator.compare(string1, string2);
              return compareResult;
    Could any one have exprience on it???
    Thanks,

    The resulted sequence
    "\u59cb\u6587\u65bc\u6709\u6c0f\u6f22\u7136\u7565\u7fa9\u800c\u81f3\u8a31\u8aaa\u91cd\u97f3"follows the traditional ordering of the Kangxi radicals within the limit of CJK Unified Ideographs.
    The following may be more flexible.
    import java.util.*;
    import java.io.*;
    import java.text.*;
    public class CharSort implements Comparator{
    java.text.RuleBasedCollator collator; // you can set your rules for the instance "collator"
    CharSort(){
      collator = (RuleBasedCollator)java.text.Collator.getInstance(java.util.Locale.TAIWAN);//try testing various locales
    public void doSort(String str) throws java.io.IOException{
    java.text.CollationKey[] keys = new java.text.CollationKey[str.length()];
    for(int i=0;i<keys.length;i++){
         keys[i] = collator.getCollationKey(str.substring(i,i+1));
    java.util.Arrays.sort(keys, this);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("cjk.txt"), "UTF8"));
    for(int i=0;i<keys.length;i++){
             bw.write(keys.getSourceString());
    bw.newLine();
    bw.close();
    public int compare(Object c1, Object c2) throws IllegalArgumentException{
    if((c1 instanceof CollationKey) &&(c2 instanceof CollationKey)){
    return collator.compare(((CollationKey)c1).getSourceString(), ((CollationKey)c2).getSourceString());
    }else throw new IllegalArgumentException();
    public boolean equals(Object c1, Object c2){
    if(this.compare(c1,c2)==0) return true;
    else return false;
    public static void main(String[] args) throws java.lang.Exception{
    CharSort chSort = new CharSort();
    String str = "\u81f3\u6f22\u8a31\u6c0f\u59cb\u6709\u8aaa\u6587\u7136\u91cd\u7fa9\u800c\u7565\u65bc\u97f3";
    chSort.doSort(str);

  • Comparing cards in a poker game?

    OK, so I was here before to ask about help for a Poker program. I got it finished thanks in large part to the people here, so I would like to say thank you very much. Now I'm furthering it by editing the Hand class to display the hand ranks (before it just displayed the hands).
    I've easily edited toString to display the rankings, now its just a matter of figuring out how to compare the cards.
    Basically, what I need to know is what would be the "best" why to compare the cards. Obviously this needs to be done by getting the card number and, for some rankings, the suit. I'm not sure of exactly how to go about this. If someone could maybe post code for just a pair (only comparing the first 2 cards) I'm sure I could figure out the rest of the rankings. If seeing my code would help (there is Card.java, Deck.java, and Hand.java, the one I'm editing) I will gladly post it. Thank you so much if anyone takes the time to help.

    this is probably way overkill for you right now, but here it is anyway. this analyzes a 7 card hand (in texas hold'em style poker). but you can see it really only tests 5 cards at a time for the best hand. hopefully it'll get you started.... i have the source for the rest of my classes too if you'd like to see it....
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Iterator;
    import java.util.TreeSet;
    * Created on Feb 22, 2005
    * Notes:
    * @author MCKNIGDM
    public class Hand {
        private static final int ASC  = 1;
        private static final int DESC = 2;
        private Card hole1;
        private Card hole2;
        private Card flop1;
        private Card flop2;
        private Card flop3;
        private Card turn;
        private Card river;
        ArrayList cards;
        Ranking ranking;
        public Hand() {
        public Hand(Card hole1, Card hole2) {
            this.hole1 = hole1;
            this.hole2 = hole2;
        public void setFlop(Card flop1, Card flop2, Card flop3) {
            this.flop1 = flop1;
            this.flop2 = flop2;
            this.flop3 = flop3;
        public void setTurn(Card turn) {
            this.turn = turn;
        public void setRiver(Card river) {
            this.river = river;
        public void rankHand() {
            placeCardsIntoArray();
            boolean suited      = false;
            int suit          = -1;
            // check for at least 5 cards of the same suit
            int count           = 0;
            Iterator itr      = null;
            if(cards.size() >= 5) {
                 for(int i=0; i<4; i++) {
                     count      = 0;
                     itr      = cards.iterator();
                     while(itr.hasNext()) { if(((Card) itr.next()).getSuit() == i) count++; }
                     if(count >= 5) {
                         suited = true;
                         suit   = i;
                         break;
            // if suited, the best hands possible are:
            //      - royal flush
            //      - straight flush
            //      - flush
            // so check for those only (the hand can't be any worse than a flush)
            if(suited) {
                // first, remove any unsuited cards from the hand
                for(int i=0; i<cards.size(); i++) {
                    if(((Card) cards.get(i)).getSuit() != suit) {
                        cards.remove(i);
                        i--;
                // now order the hand ASC - place the highest cards first
                orderArray(ASC);
                // look for a royal/straight flush
                int start = 0;
                int end = 4;
                do {
                    int rank = ((Card) cards.get(start)).getRank();
                    boolean straightFlush = false;
                    for(int i=start+1; i<=end; i++) {
                        if(((Card) cards.get(i)).getRank() == rank-1) {
                            rank--;
                        } else {
                            break;
                        if(i == end) straightFlush = true;
                    if(straightFlush) {
                        // it's either a royal or straight flush
                        ranking = new Ranking((((Card) cards.get(start)).getRank() == 14 ? Ranking.ROYAL_FLUSH : Ranking.STRAIGHT_FLUSH),
                                                (Card) cards.get(start), (Card) cards.get(start+1), (Card) cards.get(start+2), (Card) cards.get(start+3), (Card) cards.get(start+4));
                        return;
                    start++;
                    end++;
                } while(end < cards.size());
                // check for a low straight (A-2-3-4-5)
                boolean hasAce = ((Card) cards.get(0)).getRank() == Utils.ACE;
                boolean hasTwo = ((Card) cards.get(cards.size()-1)).getRank() == Utils.TWO;
                if(hasAce && hasTwo) {
                    boolean hasThree = false;
                    boolean hasFour = false;
                    boolean hasFive = false;
                    int threeIndex = -1;
                    int fourIndex = -1;
                    int fiveIndex = -1;
                    for(int k=1; k<cards.size()-1; k++) {
                        if(((Card) cards.get(k)).getRank() == Utils.THREE) {
                            hasThree = true; threeIndex = k;
                        } else if(((Card) cards.get(k)).getRank() == Utils.FOUR) {
                            hasFour = true; fourIndex = k;
                        } else if(((Card) cards.get(k)).getRank() == Utils.FIVE) {
                            hasFive = true; fiveIndex = k;
                    if(hasAce && hasTwo && hasThree && hasFour && hasFive) {
                        ranking = new Ranking(Ranking.STRAIGHT_FLUSH, (Card) cards.get(fiveIndex), (Card) cards.get(fourIndex), (Card) cards.get(threeIndex), (Card) cards.get(cards.size()-1), (Card) cards.get(0));
                        return;
                // at this point, the hand must be a flush
                // since we have all the suited cards and they are in order, just take the first 5
                ranking = new Ranking(Ranking.FLUSH, (Card) cards.get(0), (Card) cards.get(1), (Card) cards.get(2), (Card) cards.get(3), (Card) cards.get(4));
                return;
            } // end of the suited-only rankings
            // check for four of a kind
            if(checkFourKind()) return;
            // check for full house
            if(checkFullHouse()) return;
            // check for straight
            if(checkStraight()) return;
            // check for three of a kind
            if(checkThreeKind()) return;
            // check for two pair
            if(checkTwoPair()) return;
            // check for a pair
            if(checkPair()) return;
            // check for high card
            checkHighCard();
        private boolean checkHighCard() {
            Card card1 = null;
            Card card2 = null;
            Card card3 = null;
            Card card4 = null;
            Card card5 = null;
            for(int j=0; j<cards.size(); j++) {
                if(card1 == null) {
                    card1 = ((Card) cards.get(j)); continue;
                } else {
                    if(card1.getRank() < ((Card) cards.get(j)).getRank()) {
                        card1 = ((Card) cards.get(j)); continue;
                if(card2 == null) {
                    card2 = ((Card) cards.get(j)); continue;
                } else {
                    if(card2.getRank() < ((Card) cards.get(j)).getRank()) {
                        card2 = ((Card) cards.get(j)); continue;
                if(card3 == null) {
                    card3 = ((Card) cards.get(j)); continue;
                } else {
                    if(card3.getRank() < ((Card) cards.get(j)).getRank()) {
                        card3 = ((Card) cards.get(j)); continue;
                if(card4 == null) {
                    card4 = ((Card) cards.get(j)); continue;
                } else {
                    if(card4.getRank() < ((Card) cards.get(j)).getRank()) {
                        card4 = ((Card) cards.get(j)); continue;
                if(card5 == null) {
                    card5 = ((Card) cards.get(j)); continue;
                } else {
                    if(card5.getRank() < ((Card) cards.get(j)).getRank()) {
                        card5 = ((Card) cards.get(j)); continue;
            ranking = new Ranking(Ranking.HIGH_CARD, card1, card2, card3, card4, card5);
            return true;
        private boolean checkPair() {
            int pairRank   = -1;
            int count;
            // look for the largest pair
            for(int i=Utils.TWO; i<=Utils.ACE; i++) {
                count = 0;
                for(int j=0; j<cards.size(); j++) {
                    if(((Card) cards.get(j)).getRank() == i) {
                        count++;
                if(count == 2) {
                    pairRank = i;
            if(pairRank == -1) return false;
            // we have a pair -- get the pair and the 3 kickers
            Card card1 = null;
            Card card2 = null;
            Card card3 = null;
            Card card4 = null;
            Card card5 = null;
            for(int j=0; j<cards.size(); j++) {
                if(((Card) cards.get(j)).getRank() == pairRank) {
                    if     (card1 == null) card1 = (Card) cards.get(j);
                    else if(card2 == null) card2 = (Card) cards.get(j);
                    continue;
                if(((Card) cards.get(j)).getRank() != pairRank) {
                    if(card3 == null) {
                        card3 = ((Card) cards.get(j)); continue;
                    } else {
                        if(card3.getRank() < ((Card) cards.get(j)).getRank()) {
                            card3 = ((Card) cards.get(j)); continue;
                    if(card4 == null) {
                        card4 = ((Card) cards.get(j)); continue;
                    } else {
                        if(card4.getRank() < ((Card) cards.get(j)).getRank()) {
                            card4 = ((Card) cards.get(j)); continue;
                    if(card5 == null) {
                        card5 = ((Card) cards.get(j)); continue;
                    } else {
                        if(card5.getRank() < ((Card) cards.get(j)).getRank()) {
                            card5 = ((Card) cards.get(j)); continue;
            ranking = new Ranking(Ranking.PAIR, card1, card2, card3, card4, card5);
            return true;
        private boolean checkTwoPair() {
            int pair1Rank   = -1;
            int pair2Rank   = -1;
            int count;
            // look for the largest pair
            for(int i=Utils.TWO; i<=Utils.ACE; i++) {
                count = 0;
                for(int j=0; j<cards.size(); j++) {
                    if(((Card) cards.get(j)).getRank() == i) {
                        count++;
                if(count == 2) {
                    pair1Rank = i;
            if(pair1Rank == -1) return false;
            // look for the largest pair
            for(int i=Utils.TWO; i<=Utils.ACE; i++) {
                if(i == pair1Rank) continue;
                count = 0;
                for(int j=0; j<cards.size(); j++) {
                    if(((Card) cards.get(j)).getRank() == i) {
                        count++;
                if(count == 2) {
                    pair2Rank = i;
            if(pair2Rank == -1) return false;
            // we have two pair -- get the pairs and the highest kicker
            Card card1 = null;
            Card card2 = null;
            Card card3 = null;
            Card card4 = null;
            Card card5 = null;
            for(int j=0; j<cards.size(); j++) {
                if(((Card) cards.get(j)).getRank() == pair1Rank) {
                    if     (card1 == null) card1 = (Card) cards.get(j);
                    else if(card2 == null) card2 = (Card) cards.get(j);
                    continue;
                if(((Card) cards.get(j)).getRank() == pair2Rank) {
                    if     (card3 == null) card3 = (Card) cards.get(j);
                    else if(card4 == null) card4 = (Card) cards.get(j);
                    continue;
                if(((Card) cards.get(j)).getRank() != pair1Rank && ((Card) cards.get(j)).getRank() != pair2Rank) {
                    if(card5 == null) {
                        card5 = ((Card) cards.get(j));
                    } else {
                        if(card5.getRank() < ((Card) cards.get(j)).getRank()) {
                            card5 = ((Card) cards.get(j));
            ranking = new Ranking(Ranking.TWO_PAIR, card1, card2, card3, card4, card5);
            return true;
        private boolean checkStraight() {
            orderArray(ASC);
            int start = 0;
            int end = 4;
            do {
                int rank = ((Card) cards.get(start)).getRank();
                boolean straight = false;
                for(int i=start+1; i<=end; i++) {
                    if(((Card) cards.get(i)).getRank() == rank-1) {
                        rank--;
                    } else {
                        break;
                    if(i == end) straight = true;
                if(straight) {
                    ranking = new Ranking(Ranking.STRAIGHT, (Card) cards.get(start), (Card) cards.get(start+1), (Card) cards.get(start+2), (Card) cards.get(start+3), (Card) cards.get(start+4));
                    return true;
                start++;
                end++;
            } while(end < cards.size());
            // check for a low straight (A-2-3-4-5)
            boolean hasAce = ((Card) cards.get(0)).getRank() == Utils.ACE;
            boolean hasTwo = ((Card) cards.get(6)).getRank() == Utils.TWO;
            if(hasAce && hasTwo) {
                boolean hasThree = false;
                boolean hasFour = false;
                boolean hasFive = false;
                int threeIndex = -1;
                int fourIndex = -1;
                int fiveIndex = -1;
                for(int k=1; k<cards.size()-1; k++) {
                    if(((Card) cards.get(k)).getRank() == Utils.THREE) {
                        hasThree = true; threeIndex = k;
                    } else if(((Card) cards.get(k)).getRank() == Utils.FOUR) {
                        hasFour = true; fourIndex = k;
                    } else if(((Card) cards.get(k)).getRank() == Utils.FIVE) {
                        hasFive = true; fiveIndex = k;
                if(hasAce && hasTwo && hasThree && hasFour && hasFive) {
                    ranking = new Ranking(Ranking.STRAIGHT, (Card) cards.get(fiveIndex), (Card) cards.get(fourIndex), (Card) cards.get(threeIndex), (Card) cards.get(6), (Card) cards.get(0));
                    return true;
            return false;
        private boolean checkFourKind() {
            orderArray(ASC);
            int start = 0;
            int end = 4;
            do {
                int rank = ((Card) cards.get(start)).getRank();
                boolean fourKind = false;
                for(int i=start+1; i<=end-1; i++) {
                    if(((Card) cards.get(i)).getRank() == rank) {
                    } else {
                        break;
                    if(i == (end-1)) fourKind = true;
                if(fourKind) {
                    ranking = new Ranking(Ranking.FOUR_KIND, (Card) cards.get(start), (Card) cards.get(start+1), (Card) cards.get(start+2), (Card) cards.get(start+3), (Card) cards.get((start == 0 ? 4 : 0)));
                    return true;
                start++;
                end++;
            } while(end < cards.size()+1);
            return false;
        private boolean checkThreeKind() {
            int setRank   = -1;
            int count;
            // look for the largest set
            for(int i=Utils.TWO; i<=Utils.ACE; i++) {
                count = 0;
                for(int j=0; j<cards.size(); j++) {
                    if(((Card) cards.get(j)).getRank() == i) {
                        count++;
                if(count == 3) {
                    setRank = i;
            if(setRank == -1) return false;
            // we have a set -- get the 5 cards for the ranking
            Card card1 = null;
            Card card2 = null;
            Card card3 = null;
            Card card4 = null;
            Card card5 = null;
            for(int j=0; j<cards.size(); j++) {
                if(((Card) cards.get(j)).getRank() == setRank) {
                    if     (card1 == null) card1 = (Card) cards.get(j);
                    else if(card2 == null) card2 = (Card) cards.get(j);
                    else if(card3 == null) card3 = (Card) cards.get(j);
                if(((Card) cards.get(j)).getRank() != setRank) {
                    if(card4 == null) {
                        card4 = (Card) cards.get(j);
                        continue;
                    } else {
                        if(card4.getRank() < ((Card) cards.get(j)).getRank()) {
                            card4 = ((Card) cards.get(j));
                            continue;
                    if(card5 == null) {
                        card5 = (Card) cards.get(j);
                    } else {
                        if(card5.getRank() < ((Card) cards.get(j)).getRank()) {
                            card5 = ((Card) cards.get(j));
            ranking = new Ranking(Ranking.THREE_KIND, card1, card2, card3, card4, card5);
            return true;     
        private boolean checkFullHouse() {
            int setRank   = -1;
            int pairRank   = -1;
            int count;
            // look for the largest set
            for(int i=Utils.TWO; i<=Utils.ACE; i++) {
                count = 0;
                for(int j=0; j<cards.size(); j++) {
                    if(((Card) cards.get(j)).getRank() == i) {
                        count++;
                if(count == 3) {
                    setRank = i;
            if(setRank == -1) return false;
            // look for the largest pair
            for(int i=Utils.TWO; i<=Utils.ACE; i++) {
                if(i == setRank) continue;
                count = 0;
                for(int j=0; j<cards.size(); j++) {
                    if(((Card) cards.get(j)).getRank() == i) {
                        count++;
                if(count >= 2) {
                    pairRank = i;
            if(pairRank == -1) return false;
            // we have a full house -- get the 5 cards for the ranking
            Card card1 = null;
            Card card2 = null;
            Card card3 = null;
            Card card4 = null;
            Card card5 = null;
            for(int j=0; j<cards.size(); j++) {
                if(((Card) cards.get(j)).getRank() == setRank) {
                    if     (card1 == null) card1 = (Card) cards.get(j);
                    else if(card2 == null) card2 = (Card) cards.get(j);
                    else if(card3 == null) card3 = (Card) cards.get(j);
                if(((Card) cards.get(j)).getRank() == pairRank) {
                    if     (card4 == null) card4 = (Card) cards.get(j);
                    else if(card5 == null) card5 = (Card) cards.get(j);
            ranking = new Ranking(Ranking.FULL_HOUSE, card1, card2, card3, card4, card5);
            return true;
        public void placeCardsIntoArray() {
            cards = new ArrayList();
            if(hole1 != null) cards.add(hole1);
            if(hole2 != null) cards.add(hole2);
            if(flop1 != null) cards.add(flop1);
            if(flop2 != null) cards.add(flop2);
            if(flop3 != null) cards.add(flop3);
            if(turn  != null) cards.add(turn);
            if(river != null) cards.add(river);
        public void orderArray(int order) {
            TreeSet set = new TreeSet(new Comparator() {
                public int compare(Object obj1, Object obj2) {
                    Card c1 = (Card) obj1;
                    Card c2 = (Card) obj2;
                    if(c1.getRank() > c2.getRank()) {
                        return -1;
                    } else if(c1.getRank() <= c2.getRank()) {
                        return 1;
                    } else {
                        return 0;
            // add the cards to the tree set and remove from array
            while(cards.size() >= 1) {
                set.add(cards.get(0));
                cards.remove(0);
            // put the cards from the set into the array
            cards.addAll(set);
            if(order == DESC) {
                Collections.reverse(cards);
        public void printHand() {
            placeCardsIntoArray();
            orderArray(ASC);
            Iterator itr = cards.iterator();
            while(itr.hasNext()) {
                Card c = ((Card) itr.next());
                if(c.getRank() == hole1.getRank() && c.getSuit() == hole1.getSuit()) {
                    System.out.println(c.getName() + " (h1)");
                } else if(c.getRank() == hole2.getRank() && c.getSuit() == hole2.getSuit()) {
                    System.out.println(c.getName() + " (h2)");
                } else {
                    System.out.println(c.getName());
        public void printRanking() {
            if(ranking == null) System.out.println("Null ranking...");
            else ranking.printRanking();
        public Card getFlop1() {
            return flop1;
        public void setFlop1(Card flop1) {
            this.flop1 = flop1;
        public Card getFlop2() {
            return flop2;
        public void setFlop2(Card flop2) {
            this.flop2 = flop2;
        public Card getFlop3() {
            return flop3;
        public void setFlop3(Card flop3) {
            this.flop3 = flop3;
        public Card getHole1() {
            return hole1;
        public void setHole1(Card hole1) {
            this.hole1 = hole1;
        public Card getHole2() {
            return hole2;
        public void setHole2(Card hole2) {
            this.hole2 = hole2;
        public Card getRiver() {
            return river;
        public Card getTurn() {
            return turn;
        public Ranking getRanking() {
            return ranking;
    }

  • Comparator for non-standard alphabetical sorting

    Dear all,
    Default String.compareTo() method doesn't satisfy me -- alphabetical order of Latvian is slightly different from that in Unicode charts. I'm using TreeMap for indexation purposes so I implemented my own Comparator (LatvianStringComparator) to achieve correct sorting.
    Initialisation of the index is as follows:
    SortedMap index = new TreeMap(new LatvianStringComparator());Implementation of LatvianStringComparator:
    import java.io.Serializable;
    import java.util.Comparator;
    public class LatvianStringComparator implements Comparator, Serializable {
         public static final String SORT_ORDER = "a&#257;bc&#269;de&#275;fg&#291;hi&#299;jk&#311;l&#316;mn&#326;oprs�tu&#363;vz�";
         public int compare(Object o1, Object o2) {
              if (!(o1 instanceof String) || !(o2 instanceof String)) {
                   throw new ClassCastException();
              String str1 = (String)o1;
              String str2 = (String)o2;
              //Case 1: strings are equal.
              if (str1.equals(str2)) return 0;
              //Case 2: strings have to be compared char by char.
              //By default the first string is "less than" the second one.
              int signum = -1;
              int polarity = 1;
              int str1Rank = -1;
              int str2Rank = -1;
              if (str2.length() < str1.length()) {
                   //Primary string is the shortest one; polarity changes.
                   String temp = str1;
                   str1 = str2;
                   str2 = temp;
                   polarity = -1;
              for (int i = 0; i < str1.length(); i++) {
                   str1Rank = SORT_ORDER.indexOf(str1.charAt(i));
                   str2Rank = SORT_ORDER.indexOf(str2.charAt(i));
                   //If char is not present in the specified alphabeth,
                   //it's Unicode position is taken; SORT_ORDER.length() = offset.
                   if (str1Rank == -1) {
                        str1Rank = str1.charAt(i) + SORT_ORDER.length();
                   if (str2Rank == -1) {
                        str2Rank = str2.charAt(i) + SORT_ORDER.length();
                   if (str2Rank < str1Rank) {
                        //First string is "greater than" the second one.
                        signum = 1;
                        break;
              return signum * polarity;
    PROBLEM:
    For small set of keys (tested on several elements) sorting seems to work well, but in case of large number of keys (> 10K) order is strange and fragmented. I'm sure that the problem is not in the number of keys.
    Another issue: many values for keys appear as null!
    If I remove new LatvianStringComparator() from the param list of TreeMap constructor, my app works fine except the sorting according the Latvian alphabeth. So I asume that my implementation of Comparator is erroneous or I have misunderstood something conceptually.
    Could anybody inspect the code, please? THANK YOU!!!
    Normunds

    Hi,
    even this small code fails:
            SortedMap index = new TreeMap(new LatvianStringComparator());
            index.put("baa", "baa");
            index.put("aaa", "aaa");
            index.put("aqa", "aqa");
            index.put("caa", "caa");
            Iterator it = index.keySet().iterator();
            while (it.hasNext()) {
                String key = (String)it.next();
                System.out.println(key);
            }because you assume '...first string is "less than" the second one'
    but you did not test it.
    Just add a 'less test' like:
    if (str2Rank > str1Rank) {
    //First string is "less than" the second one.
    signum = -1;
    break;
    }after
    if (str2Rank > str1Rank) {}and your code will work.
    even better: use Collator API
    Franco

  • Userdefined Sorting the objects using comparator

    Hi All,
    I want to display the objects in a userdefined order. I have placed the code snippet below. Kindly help me on this to resolve this issue.
    public class ApplicabilityObject1 implements Comparable{
         private String str;
         public ApplicabilityObject1(String str) {
              this.str = str;
         public boolean equals(Object obj) {
              return getStr().equals(((ApplicabilityObject1)obj).getStr());
         public String toString() {
              return str;
         public String getStr() {
              return str;
         public void setStr(String str) {
              this.str = str;
         public int compareTo(Object arg0) {
              final int equal = 0;
              final int before = -1;
              final int after= 1;
              int returnvalues  = 0;
              System.out.println(this);
                                    if ("Mexico"==((ApplicabilityObject1)arg0).getStr())
                   returnvalues = -1;
              else if (((ApplicabilityObject1)arg0).getStr()== "Canada")
                   returnvalues =  0;
              else if (((ApplicabilityObject1)arg0).getStr()== "USA")
                   returnvalues = 1;
              return returnvalues;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    /*import org.apache.commons.beanutils.BeanComparator;
    import org.apache.commons.collections.comparators.FixedOrderComparator;*/
    public class SortOrder {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              APPComparator app1 = new APPComparator();
              ApplicabilityObject1 obj1 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj2 = new ApplicabilityObject1("Canada");
              ApplicabilityObject1 obj3 = new ApplicabilityObject1("USA");
              ApplicabilityObject1 obj4 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj5 = new ApplicabilityObject1("USA");
              ApplicabilityObject1 obj6 = new ApplicabilityObject1("USA");
              ApplicabilityObject1 obj7 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj8 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj9 = new ApplicabilityObject1("Canada");
              List list = new ArrayList();
              list.add(obj1);
              list.add(obj2);
              list.add(obj3);
              list.add(obj4);
              list.add(obj5);
              list.add(obj6);
              list.add(obj7);
              list.add(obj8);
              list.add(obj9);
              Collections.sort(list, app1);
              System.err.println(list);
              System.out.println(Integer.MAX_VALUE);
    class APPComparator implements Comparator
         ApplicabilityObject1 appO = new ApplicabilityObject1("USA");
         @Override
         public int compare(Object arg0, Object arg1) {
              // TODO Auto-generated method stub
              return ((ApplicabilityObject1)arg0).compareTo(arg1);
    }I'm expecting the result in the Order of USA, CANADA, MEXICO.
    But now the above code giving the result of [USA, USA, USA, Mexico, Canada, Mexico, Mexico, Mexico, Canada]
    Kindly help me to resolve this issue.
    Thanks in advance,
    Maheswaran

    An alternative way to reduce the size of your code.
    //Un-Compiled
    ApplicabilityObject1[] appObs = {
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("Canada"),
      new ApplicabilityObject1("USA"),
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("USA"),
      new ApplicabilityObject1("USA"),
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("Canada")};
    List list = new ArrayList(Arrays.asList(appObs));Mel

Maybe you are looking for

  • Has anyone had a problem with printing from Elements 9 on a MAC?

    When I first installed Elements 9 and tried to print, all I got were blank pages.  I contacted adobe support and after an hour on the  phone, she referred me to the next level.  I then received an email from them asking me to call them and in the mea

  • Starting BPM process instance automatically

    In our process we would like to read the Oracle staging table and start the instance(s). We want this to happen every hour or so automatically. We looked into documentation for starting the instances. Looks like there are only two ways, one is throug

  • Verizon does not know what customer service means

    I tried to pay my bill online using the Verizon gift card that I received when I signed up for Verizon Fios. It would not let me do it. I got an error message that my payment transaction failed because of an invalid card or authorization is decline b

  • Internal Error 2502 - JRE (Java SE Runtime 5.02u22) ...please help!

    Hi Everyone, I am setting up an account to submit documents to the FDA through an electronic submission gateway. It's been one thing after the other. I finally made progress on the checklist. The next requirement is to download JRE and JCE. Anytime I

  • Dll in form6i urgent

    how to controll or link a personal created dll through form6i. i used a dll in vb6 to communicate on parallel port. now i want to use that dll in form 6i. if any one can give any solution plz hep