Generic Comparer Implementation

Hi, I am trying to implement a generic comparer, as you can see (from the code below), this is probably the most raw / bad form of an implementation. I want it to work for all types, used if conditions for each data type, then realized that I am heading
in the wrong direction. There must be an efficient way of writing it.
I was trying to see if I can look at how Comparer<T> was implemented which derives from IComparer and IComparer<T>. But the code is not visible. Perhaps using reflection, might be possible. But I want to understand the idea behind a good comparer
solution. Any help is much appreciated
Thanks
public class MyGenericComparer<T>
public int Compare(T x, T y)
if (typeof(T) == typeof(String))
return ((string)(object)x).CompareTo((string)(object)y);
if (typeof(T) == typeof(int))
return ((int)(object)x).CompareTo((int)(object)y);
return -999;

In case you are asking what the good of an IComparer<T> is, this is the answer.
IComparer<T> is provided in order to let developers use any comparison algorithms they prefer when instances of their classes or types are about to being compared. For example in an array of Product type, the default comparison for Product instances
is compare based on reference, because they are object (reference-types).
But, many scenarios exist that you might not want your objects are compared based on their reference. Suppose you want to sort your array of products based on their Weight, Price, Title, StockDate or whatever rule you might want.
IComparer<T> is for such occasions. You can implement this interface in a class and give an instance of it to Array.Sort(). Then the array uses your custom comparer to sort your objects. 
class Product
public string Title;
public float Price;
public int Code;
public bool InStock;
public Product(string title, float price, int code, bool inStock)
Title = title;
Price = price;
Code = code;
InStock = inStock;
class ProductPriceComparer: System.Collections.IComparer, System.Collections.Generic.IComparer<Product>
// unchanged sections omitted
public int Compare(Product x, Product y)
if ((x == null) && (y == null))
return 0; // null is equal to null
if (x == null)
return -1; // null is lower than anything
if (y == null)
return 1; // anything is greater than null
int result;
if (x.Price > y.Price)
result = 1;
else if (x.Price < y.Price)
result = -1;
else
result = 0;
return result;
Product[] products = new Product[]
new Product("HTC Desire S", 590.0f, 10025, true),
new Product("Sony Ericsson Xperia Neo", 590.0f, 10032, true),
new Product("Nokia X7", 570.0f, 10021, true),
new Product("Motorola Atrix", 830.0f, 10034, false),
new Product("LG Optimus One P500", 270.0f, 10035, true),
new Product("Samsung I9100 Galaxy", 800.0f, 10029, true),
new Product("Apple iPhone 4", 900.0f, 10024, false),
new Product("Asus Eee Pad Transformer TF101", 750.0f, 10028, true),
new Product("Archos 101 Internet Tablet", 450.0f, 10030, true)
Product p;
Console.WriteLine("\nSort by price…");
Array.Sort(products, new ProductPriceComparer());
for (int i = 0; i < products.Length; i++)
p = products[i];
Console.WriteLine("{0}: {1} ({2}$)", i + 1, p.Title, p.Price);
You can implement as many comparer as you want.

Similar Messages

  • Generic Comparator problem

    Hi!
    In our code we use Comparator, but can not make it work with generics.
    The only way is to insert cast in some places, but that destroy the point in using generics in the first place.
    Basically we have a superclass Foo and child classes FooA, FooB, FooC etc. (FooX extends Foo)
    In Foo there is a method that needs to compare two FooX objects (they are always both of the same type).
    So Foo declares an abstract method getComparator() and then calls compare() from it.
    The current code is like this :
    public abstract class Foo {
        public abstract Comparator<? extends Foo> getComparator();
        private int doAndCompare(Foo newFoo) {
            if (0 == this.getComparator().compare(this, newFoo)) {
             // some code ...
    // each FooX is like this
    public class FooA extends Foo {
        static Comparator<FooA> myComparator = new Comparator<FooA>() {
            public int compare(FooA one, FooA two) {
                // the computation is specific for each FooX
                return xxx; // compute and return some int value
        public Comparator<FooA> getComparator() {
            return  myComparator;
    }This code has a compile error in the if statement:
    The method compare(capture-of ? extends Foo, capture-of ? extends Foo) in the type Comparator<capture-of ? extends Foo> is not applicable for the arguments (Foo, Foo)
    I could use "super" instead of "extends" in the getComparator() definition, but the each FooX would have an error, which are solvable only by casting.
    Is there a cast-less solution ?

    This might not be the post that will answer your question (since I honestly do not completely get your question), but might provide some (to) creative insights.
    A weird construct that will work without casting (but probably not very useful):
    public static void main(String[] args) {
         FooX x1 = new FooX();
         FooX x2 = new FooX();
         // requires a parameter of type FooX
         x1.doAndCompare(x2);
         FooY y1 = new FooY();
         FooY y2 = new FooY();
         // requires a parameter of type FooY
         y1.doAndCompare(y2);
         Foo f1 = new FooY();
         Foo f2 = new FooY();
         f1.doAndCompare(y2); // requires a parameter of type Foo, so no actual benifit here? Will work though
         f1.doAndCompare(x2); // Will throw a ClassCastException, so not very usable
    static abstract class Foo<T extends Foo<?>> implements Comparable<T> {
         public void doAndCompare(T foo) {
              if (0 == this.compareTo(foo)) {
                   // do your magic
    static class FooX extends Foo<FooX> {
         public int compareTo(FooX o) {
              // TODO Auto-generated method stub
              return 0;
    static class FooY extends Foo<FooY> {
         public int compareTo(FooY o) {
              // TODO Auto-generated method stub
              return 0;
    }An example that works with casting and that will work:
    public static void main(String[] args) {
         FooX x1 = new FooX();
         FooX x2 = new FooX();
         // requires a parameter of type Foo, FooX.compareTo(FooX) will be invoked
         x1.doAndCompare(x2);
         FooY y1 = new FooY();
         FooY y2 = new FooY();
         // requires a parameter of type Foo, FooY.compareTo(FooY) will be invoked
         y1.doAndCompare(y2);
         // requires a parameter of type Foo
         y1.doAndCompare(x2); // will work
    static abstract class Foo implements Comparable<Foo> {
         public void doAndCompare(Foo foo) {
              if (0 == this.compareTo(foo)) {
                   // do your magic
    static class FooX extends Foo {
         public int compareTo(Foo foo) {
              if (foo instanceof FooX) {
                   return this.compareTo((FooX) foo);
              } else {
                   return 1; // return what's apropriate of not equal
         public int compareTo(FooX fooX) {
              return 0;
    static class FooY extends Foo {
         public int compareTo(Foo foo) {
              if (foo instanceof FooY) {
                   return this.compareTo((FooY) foo);
              } else {
                   return 1; // return what's apropriate of not equal
         public int compareTo(FooY fooY) {
              return 0;
    }I couldn't help noticing that in your original post you very specifically used 'if comparision == 0'. That looks a lot like Foo.equals() to me. Isn't that just what you want?

  • Generic Comparator compile issue

    hi
    In JDeveloper 10.1.3.2.0.4066 this code ...
    package genericcomparatorcompileissue;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.LinkedList;
    import java.util.List;
    public class GenericComparatorCompileIssue
         private static interface MyRow {};
         private static class MyRowImpl implements MyRow {};
         private static class MyRowComparator implements Comparator<MyRowImpl>
              public int compare(MyRowImpl pFirstMyRowImpl, MyRowImpl pSecondMyRowImpl)
                   return 0;
         public static void main(String[] pArguments)
              System.out.println("GenericComparatorCompileIssue.main() : begin");
              List<MyRow> vMyRowList = new LinkedList<MyRow>();
              Collections.sort(vMyRowList, new MyRowComparator());
              System.out.println("GenericComparatorCompileIssue.main() : end");
    }... compiles and runs and produces this output:
    GenericComparatorCompileIssue.main() : begin
    GenericComparatorCompileIssue.main() : endBut if you check the "Use Javac" Compiler option in the Project Properties dialog, the compiler reports a "cannot find symbol" error at line 25.
    How can this be explained?
    many thanks
    Jan Vervecken

    This problem has been reported as
    BUG 6311332 - OJC ALLOWS WRONG PARAMTERS FOR COLLECTIONS.SORT(...)
    This bug will be fixed with JDeveloper 11. (It is not yet fixed with the development preview!)
    As a workaround you can use javac instead of ojc for compilation. javac will report such wrong assignments. You need to compile with ojc only if you want to use JDeveloper profiling or code coach.

  • Generic comparator in container search

    I have an application where I'm using a Stack to store heterogeneous objects, some of which might be Comparable. I occasionally have need to search(obj) the stack for some object that might or might not be there. The object might be comparable.
    I have one particular class (which shall remain anonymous) whose comparator, in a wonderful display of software engineering theory, throws an IllegalArgumentException when compared to something it can't compare to, instead of returning false.
    Now it would be nice to be able to just send a Comparator to the search() method (or to any other container's lastIndexOf(), etc.) so that I can do some arbitrarily smart comparison, or arbitrarily stupid one. Why can't I?!?!?!!
    Now in this case, what I've resorted to doing is writing a wrapper class that has a compareTo method that compares class strings first, then catches such silly things if they happen.
    Is there an easier way? Should I submit a feature request for these comparing methods to optionally take a Comparator?
    Thanks,
    Gremio

    Why can't I?!?!?!!Because not all the objects in the stack might be Comparable. Because the search method is designed to look for an object - with identification by equals.
    Is there an easier way? Sure, violate the equals() contract and pass into search an object which returns true when equals is called with any object you're interested in.
    By the way, please tell your software engineering theorist that the API says (s)he should throw ClassCastException.

  • CProjects 4.0 performance - questionaire to compare implementations

    Hi All,
    Just looking to get a comparison of performance of 4.0 installations. In my company, it is not going very well and if we don't see a major performance boost soon, I don't see that anyone will every use this tool. So, I have a simple list of activities to perform, just looking to get feedback from other 4.0 installations to see what the average times are for each of these activities - as a set of sample activities. I have posted in this also my avg. response times from the system. in [seconds]. We have done extensive Network and Server analysis and can really only link the slow performance back to the application itself... We are on SP9 currently.
    Note: Our standard project template has about 290 tasks - this makes a major difference when changing information in the table view fully expanded - a typical way of working with the tool.
    1.) Click on project from cProjects Project Dashboard, time how long from click until project is open [4.3s]
    2.) Select the 'Project Element' (triangle) and click on the 'Expand Subtree' icon, time from click until it is fully expanded [4.6s]
    3.) Once Tree is expanded, click on 'Table' view, time how long until Table View is completely loaded [8.5s]
    4.) Change a role for a task and select 'TPL/System' from list, time how long it takes from the time you select the drop down until the time the system applies the Role. (Try this with a role that has staffing) [8.1s]
    5.) Enter a start date (5a), hit enter and time how long it takes for the system to process it, do the same for a finish date (5b) [52s/50s]
    6.) In the Table View still, select the side scroll bar and scroll (select and slide the scroll bar) to the bottom of the table, time how long it takes for the system to process the request. [8.4s]
    7.) Click on the Gantt Chart (while in Table View and tree expanded), time how long until the Gantt Chart is completely loaded [37s]
    8.) In Gantt Chart, select a task (F55 PCIS) and move the bar over 3 days and release, time how long it takes from the time you release to the time the system is completed processing [16s]
    9.) Go Back to Detail View and select a task, from basic data, change the Status from Released to In Process, time how long it takes for the system to finish processing [9.8s]
    10.) Go to the documents tab, create a new document and use the attached file in this email to attach. Put 'Test' in for description and time how long it takes for the system to finish processing the attachment [9.5s]
    11.) Under Resources Tab, select a Role, select the 'Staffing' tab. put a resource number (any) into the resource field and click 'Staff', time how long it takes to process the staffing [4.8s]

    > I made a report zreport_2 & executed both of them in background simultaneously to compare the time
    this was really no good idea.
    If you insert anything to the database, then you get a dump, if you try to times the same.
    Even if you don't change anything then the parallel processing will not show anything the only try to get the resources.
    You must execute them onne by one.
    Run traces of both executions, execute every version at least three times (first one more expensive, second and third similar otherwise repeat)
    SQL trace:
    /people/siegfried.boes/blog/2007/09/05/the-sql-trace-st05-150-quick-and-easy
    SE30
    /people/siegfried.boes/blog/2007/11/13/the-abap-runtime-trace-se30--quick-and-easy
    The SE30 shows everything what was going on, the SQL trace only the db part.
    Check the summary by SQL statements, this is small, and youi can compare both executions by hand.
    The SE30 hitlist is large, but there is a tool to compare then, see here:
    Z_SE30_COMPARE
    /people/siegfried.boes/blog/2008/01/15/a-tool-to-compare-runtime-measurements-zse30compare
    Siegfried

  • Implementing  Comparable with Generics

    Hi,
         I would like to implement a generic class containing two elements that would be sorted according to the second element. I get a compilation error on the last line of the code.
    public class Pair <T , U> implements Comparable
       private final T first;
       private final U second;
       public  Pair( T f, U s )
        this.first = f;
        this.second = s;
       public Pair () {
            this.first = null;
            this.second = null;
       public T getFirst()
        return first;
       public U getSecond()
        return second;
       @Override
       public int compareTo(Object oth) {
            if ( this == oth ) {
               return 0;
             if ( oth == null ) {
               throw new NullPointerException();
             if(!(getClass().isInstance( oth ))) {
                  throw new IllegalArgumentException();
             Pair<T, U> other = this.getClass().cast( oth );
             if(this.getSecond() == other.getSecond()) {
                  return 0;
             else {
                  //The following line does not compile
                  return (this.getSecond() > other.getSecond()) ? 1 : -1;
    }How do I ensure that the second object U implements the comparable interface. If I do something like
    public class Pair <T , U implements Comparable> implements Comparableit does not compile?
    Thank you for your ideas.
    O.O.

    edit: scratch that
    How about:
    public class Pair <T , U extends Comparable<U>> implements Comparable<Pair<T, U>>
       public int compareTo(Pair<T, U> oth) {
          else {
            return (this.getSecond().compareTo(other.getSecond()));
          }Edited by: Encephalopathic on Jul 11, 2008 5:23 PM

  • Comparator for Generic Sorting

    Hi,
    I have a number of reports for which sorting is required on all columns. Each of these reports has a corresponding class, the columns correspond to the attributes of the class
    Arrays.sort(Object[] objArray,Comparator c) is used for the sorting.
    I have a generic class implementing Comparator interface.
    The compare(Object o1,Object o2 ) method of this class retrieves the values of the columns on which the comparison is to be made as:
    Object val1=Class.forName(o1.getClass().getName()).getMethod(methodName,null).invoke(o1,null);
    Object val2=Class.forName(o2.getClass().getName()).getMethod(methodName,null).invoke(o2,null);
    where methodName is the name of the accessor method for the column. val1 and val2 are then compared.
    The question is whether a generic comparator class can be implemented without using the reflection mechanism.
    Thanks ,
    Pratibha

    sure, use an interface and upcasting
    interface HasColumn {
      Object getColumn();
    Object val1 = ((HasColumn)o1).getColumn();
    Object val2 = ((HasColumn)o2).getColumn();Be sure that either all Objects in the Array implement HasColumn,
    or check instanceof HasColumn / catch the ClassCastException and do alternative comparing in the case of an "alien" Object.

  • Compare to 1 Uncheked warning - Needs generics

    I get an "unchecked" warning when compiling (for failing to use generics...). Please help me with this (optimally by revising my code to be generics compliant)! Not that I am quite unfamiliar with generics, and hence could not revise this myself, a brief explanation of your revisions would also be nice.
    public static void sort(Comparable[] array) { //suppress warning for failing to use generics
        Comparable smallest = array[0]; //stores the smallest object
        int smallestLocation = 0; //stores the index of the smallest object
        for (int front = 0; front < array.length-1;front++) {
          smallest = array[front]; //reset variables
          smallestLocation = front;
          for (int i = front;i < array.length;i++) {
            if (smallest.compareTo(array) > 0) { //this if statement sets the smallest location based on comparing every element in the array *error occurs here*
    smallest = array[i];
    smallestLocation = i;
    swap(front,smallestLocation,array); //puts the smallest element at the front of the array
    }Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    MakingGUIs wrote:
    I have read those! You must have tired out near the end, then. The relevant section (I think) is here:
    [http://java.sun.com/docs/books/tutorial/extra/generics/fineprint.html|http://java.sun.com/docs/books/tutorial/extra/generics/fineprint.html]
    which is near the end of the second tutorial you say you read. (The section headed "Arrays"...) However, frankly, I would modify the method to look like this:
    public static void sort(Object[] array) {
      Arrays.sort(array);
    }

  • Gnerics problem with Comparator

    i have to creat a program which deals with LinkedList...but I'll creat my own list which its name is "InOrderLinkedList"
    it's function is to take numbers and put them in the right order node
    i made 2 codes but one of them has an error (which i think it's about Generic Comparator Problem)
    and the other code doesn't have any error...but doesn't do any thing when i run it
    first code is:_
    import java.util.Collections;
    import java.util.List;
    import java.util.*;
    import java.util.Iterator;
    import java.util.ListIterator;
    import java.lang.Integer;
    import java.lang.Object;
    import java.lang.*;
    import javax.swing.*;
    class Node<E>{
              E item_;
              Node nextNode_=null;
              public void setItem(E item){
                   item_=(E)item;
              public Node<E> getNextNode(){
                   return nextNode_;
              public void setNextNode(Node nextNode){
                   this.nextNode_=nextNode;
              public String toString(){
                   return item_.toString();
              E getItem(){
                   return (E)item_;
    /*interface Comparator<E>{
         public int compareTo(E e1,E e2);
    class Comp implements Comparator <Integer>{
         public int compare(Integer e1,Integer e2){
         return e1-e2;
    class LinkedListme<E>{
         Node<Integer> head;
         Node<Integer> tail;
         int size=0;
         public void addFirst(int e){
              /*Node<E> node= new Node<E> (e);
              node.setNextNode(head);
              head=node;
              size++;*/
         public void addLast(int e){
              /*Node<E> node=new Node<E> (e);
              if(head==null){
                   head=node;
                   size++;
                   return;*
              Node<E> lastNode=head;
              while(lastNode.getNextNode()!=null){
                   lastNode=lastNode.getNextNode();
              lastNode.setNextNode(node);*/
         public void clear(){
              head=null;
              size=0;
         public int removeFirst(){
              Node<Integer> firstNode=head;
              head= head.getNextNode();
              size--;
              return firstNode.getItem();
         public int removeLast(){
              if (size==1)
                   return removeFirst();
              if (size==0)
                   return 0;
              Node<Integer> secondLast=head;
              Node<Integer> lastNode=null;
              while(secondLast.getNextNode().getNextNode()!=null){
                   secondLast=secondLast.getNextNode();
              lastNode=secondLast.getNextNode();
              secondLast.setNextNode(null);
              size--;
              return lastNode.getItem();
         public int remove(int index){
              Node<Integer> beforeRemoved=head;
              Node<Integer> removed=null;
              for(int i=1;i<(index-1);i++){
                   beforeRemoved=beforeRemoved.getNextNode();
              removed=beforeRemoved.getNextNode();
              beforeRemoved.setNextNode(removed.getNextNode());
              return removed.getItem();
         public void add(int index,int x){
              /*Node<E> beforeAdd=head;
              Node<E> newNode=new Node<E> (x);
              for(int i=1;i<(index-1);i++){
                   beforeAdd=beforeAdd.getNextNode();
              newNode.setNextNode(beforeAdd.getNextNode());
              beforeAdd.setNextNode(newNode);*/
         /*public void prnt(LinkedListme<E> l){
              System.out.print(l);
    public class InOrderLinkedList <E> extends LinkedListme<E>{
         public void add (int elem){
              Node <Integer> newNode = new Node <Integer>();
              newNode.setItem(elem);
              if(head==null){
                   head=newNode;
                   tail=newNode;
                   newNode.setNextNode(head);
                   head=newNode;
    //public class LinkedListme {
    public static void main(String[]args){
         InOrderLinkedList <Integer> list=new InOrderLinkedList <Integer>();
         Comp com=new Comp();
         list.add(5);
         list.add(5);
         list.add(3);
         list.add(6);
         list.add(3);
         list.add(2);
         list.add(1);
         Collections.sort(list,com); ///here is the error
         System.out.println(list.toString());
    the second code is:_
    import java.util.*;
    import java.util.Iterator;
    import java.util.ListIterator;
    import java.lang.Integer;
    import java.lang.*;
    import javax.swing.*;
    class Node<E>{
              E item_;
              Node <E>nextNode_=null;
              public void setItem(E item){
                   item_=(E)item;
              public Node<E> getNextNode(){
                   return nextNode_;
              public void setNextNode(Node <E>nextNode){
                   this.nextNode_=nextNode;
              public String toString(){
                   return item_.toString();
              E getItem(){
                   return (E)item_;
    /*interface Comparator<E>{
         public int compareTo(E e1,E e2);
    class Comp implements Comparator <Integer>{
         public int compare(Integer e1,Integer e2){
         return e1-e2;
    class LinkedListme<E>{
         Node<Integer> head;
         Node<Integer> tail;
         int size=0;
         public void addFirst(int e){
              /*Node<E> node= new Node<E> (e);
              node.setNextNode(head);
              head=node;
              size++;*/
         public void addLast(int e){
              /*Node<E> node=new Node<E> (e);
              if(head==null){
                   head=node;
                   size++;
                   return;*
              Node<E> lastNode=head;
              while(lastNode.getNextNode()!=null){
                   lastNode=lastNode.getNextNode();
              lastNode.setNextNode(node);*/
         public void clear(){
              head=null;
              size=0;
         public int removeFirst(){
              Node<Integer> firstNode=head;
              head= head.getNextNode();
              size--;
              return firstNode.getItem();
         public int removeLast(){
              if (size==1)
                   return removeFirst();
              if (size==0)
                   return 0;
              Node<Integer> secondLast=head;
              Node<Integer> lastNode=null;
              while(secondLast.getNextNode().getNextNode()!=null){
                   secondLast=secondLast.getNextNode();
              lastNode=secondLast.getNextNode();
              secondLast.setNextNode(null);
              size--;
              return lastNode.getItem();
         public int remove(int index){
              Node<Integer> beforeRemoved=head;
              Node<Integer> removed=null;
              for(int i=1;i<(index-1);i++){
                   beforeRemoved=beforeRemoved.getNextNode();
              removed=beforeRemoved.getNextNode();
              beforeRemoved.setNextNode(removed.getNextNode());
              return removed.getItem();
         public void add(int index,int x){
              /*Node<E> beforeAdd=head;
              Node<E> newNode=new Node<E> (x);
              for(int i=1;i<(index-1);i++){
                   beforeAdd=beforeAdd.getNextNode();
              newNode.setNextNode(beforeAdd.getNextNode());
              beforeAdd.setNextNode(newNode);*/
         /*public void prnt(LinkedListme<E> l){
              System.out.print(l);
    public class InOrderLinkedList <E> extends LinkedListme<E>{
         Comp com=new Comp();
         public void add (int elem){
              Node <Integer> newNode = new Node <Integer>();
              newNode.setItem(elem);
              if(head==null){
                   head=newNode;
                   tail=newNode;
              if(com.compare(head.getItem(), elem)>=0){
                   newNode.setNextNode(head);
                   head=newNode;
                   return;
                   Node<Integer> lastNode=head;
                   //Integer lastNodeInt=(Integer)lastNode;
              int compVal=com.compare(lastNode.getItem(), elem);
              while(compVal<0 && lastNode.getNextNode()!=null){
                   lastNode=lastNode.getNextNode();
              if(lastNode.getNextNode()==null){
                   lastNode.setNextNode(newNode);
              tail=newNode;     
              else{
                   newNode.setNextNode(lastNode.getNextNode());
                   lastNode.setNextNode(newNode);
    //public class LinkedListme {
    public static void main(String[]args){
         InOrderLinkedList <Integer> list=new InOrderLinkedList <Integer>();
         list.add(5);
         list.add(9);
         list.add(3);
         list.add(6);
         list.add(3);
         list.add(2);
         list.add(1);
         System.out.println(list.toString());
    what are thier problems??
    thanks

    So what's the error message?

  • LINQ grouping with custom comparer

    I'm trying to implement a linq grouping with a custom comparer. I have a datatable, I fill it with data, then I add the datarows to a
    List(Of DataRow), then I select all the rows to a IEnumerable(Of Object()). After that, I would like to group the result with a custom comprarer.
    This is the code:
    Dim result As IEnumerable(Of Object())
    Dim dt As New DataTable
    Dim indexes As New List(Of Integer)
    Dim groupedindexes As New List(Of Integer)
    Dim datarows As New List(Of DataRow)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    dt.Columns.Add("f1", Type.GetType("System.Char"))
    dt.Columns.Add("f2", Type.GetType("System.Char"))
    dt.Columns.Add("f3", Type.GetType("System.Char"))
    For i = 0 To 100
    dt.Rows.Add("a", "b", "c")
    Next
    indexes.Add(0)
    indexes.Add(1)
    indexes.Add(2)
    groupedindexes.Add(0)
    groupedindexes.Add(1)
    groupedindexes.Add(2)
    For i = 0 To dt.Rows.Count - 1
    datarows.Add(dt.Rows(i))
    Next
    result = datarows.Select(Function(row) indexes.Select(Function(index) row(index)).ToArray)
    Dim test = result.GroupBy(Function(row) groupedindexes.Select(Function(grpindex) row(grpindex)).ToArray, New compare)
    End Sub
    And this is the compare class:
    Partial Class compare
    Implements System.Collections.Generic.IEqualityComparer(Of Object())
    Public Function Equals1(ByVal x() As Object, ByVal y() As Object) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of Object()).Equals
    Dim equal As Boolean = True
    For i = 0 To x.Count - 1
    If x(i) IsNot y(i) Then
    equal = False
    Exit For
    End If
    Next
    Return equal
    End Function
    Public Function GetHashCode1(ByVal obj() As Object) As Integer Implements System.Collections.Generic.IEqualityComparer(Of Object()).GetHashCode
    Dim hashcode As Integer
    For i = 0 To obj.Count - 1
    hashcode = hashcode + obj(i).GetHashCode
    Next
    Return hashcode
    End Function
    End Class
    With the above code, I get all the 101 rows, but I would like to get only one row (a, b, c), since all the rows are the same. Therefore I wrote the custom comparer class. I'm new to this and I'm not sure, that I use it correct.
    Can you advise me, how should I modify the code to get only one row?
    Thanks.

    Try code below.  I use a dictionary to group rows and then filter results to get unique rows.
    Module Module1
    Sub Main()
    Dim dt As New DataTable
    Dim dict As Dictionary(Of Integer, List(Of DataRow)) = dt.AsEnumerable() _
    .GroupBy(Function(x) x.Field(Of Integer)("Col A"), Function(y) y) _
    .ToDictionary(Function(x) x.Key, Function(y) compare(y.ToList()))
    End Sub
    Function compare(rows As List(Of DataRow)) As List(Of DataRow)
    Dim results As New List(Of DataRow)
    results.Add(rows.FirstOrDefault)
    If (rows.Count > 1) Then
    For i = 1 To (rows.Count - 1)
    Dim unique As Boolean = True
    Dim rowArray() As Object = rows(i).ItemArray
    For j = 0 To (results.Count - 1)
    Dim oldArray() As Object = results(j).ItemArray
    For cols = 0 To (rowArray.Length - 1)
    If rowArray(i) <> oldArray(j) Then
    unique = False
    Exit For
    End If
    Next cols
    If unique = False Then
    Exit For
    End If
    Next j
    If unique = True Then
    results.Add(rows(i))
    End If
    Next i
    End If
    Return results
    End Function
    End Module
    jdweng

  • D-ary heap with Priority Queue implementation

    I have to construct a program that find the k-th smallest integer in a given set S of numbers; read from the standard input a first line containing positive integers N, k, and d separated by spaces. Each of the following N lines contains a positive integer of the set S. I have to implement a generic d-ary heap class that implements all methods of the priority queue interface.
    i have the following code...but the inserting bubbling doesnt seem to wokr right...
    any help would be great:
    import java.util.*;   
    public class Heap {
        static Element[] heap;
        int N;
        static int k;
        int d;
        static int size = 0;
        Compare comp;
        public Heap(int nodes, int max, Compare c)
            N = max;
            d = nodes;
            heap = new Element[N];
            comp = c;
        public static void main(String args[])
            Scanner _scan = new Scanner(System.in);
      //      String Nkd = _scan.nextLine();
       //     Scanner _scanNkd = new Scanner(Nkd);
            int _N = 0;
            int _d = 0;
            Compare _c = new Compare();
                _N = _scan.nextInt();
                k = _scan.nextInt();
                _d = _scan.nextInt();
            Heap _heap = new Heap(_d,_N,_c);
            int i=0;
            int num=0;
            while(_scan.hasNextLine()&&num<_N)
                System.out.println("test" + _scan.nextInt());
                _heap.insert(i, _scan.nextInt());
                i++;
                size++;
                num++;
            for(int z=0;z<_N;z++)
            //    System.out.println(heap[z].getKey());
            Element kth = null;
            for(int j = 1; j <=k; j++)
                kth = _heap.removeMin();
            System.out.print(kth.getKey());
            System.out.print('\n');
            /*System.out.print(k);
            System.out.print('\n');
            System.out.print(_heap.size());
            System.out.print('\n');
            System.out.print('\n');
            System.out.print(heap[0].getKey());
            System.out.print('\n');
            System.out.print(heap[1].getKey());
            System.out.print('\n');
            System.out.print(heap[2].getKey());
            System.out.print('\n');
            System.out.print(heap[3].getKey());
            System.out.print('\n');
            System.out.print(heap[4].getKey());
            System.out.print('\n');
            System.out.print(heap[5].getKey());*/
        public void insert(int i, int e)
            heap[i] = new Element(e,i);
            this.bubbleUp(heap);
    public int size() {return size;}
    public boolean isEmpty() {return(size == 0);}
    public int min(){return heap[0].getKey();}
    public Element remove()
    int i = size-1;
    size--;
    return heap[i];
    public Element removeMin()
    Element min = this.root();
    if(size == 1)
    this.remove();
    else
    this.replace(this.root(), this.remove());
    this.bubbleDown(this.root());
    return min;
    public Element replace(Element a, Element b)
    a.setIndex(b.getIndex());
    a.setKey(b.getKey());
    return a;
    public void bubbleUp(Element e)
    Element f;
    while(!e.isRoot(e.getIndex()))
    f = this.getParent(e.getIndex());
    if(comp.compare(f,e) <= 0)
    break;
    else
    int temp = f.getIndex();
    f.setIndex(e.getIndex());
    e.setIndex(temp);
    swap(f,e);
    System.out.println("bubbling");
    e=f;
    public void bubbleDown(Element e)
    int i = e.getIndex();
    while(e.isInternal(i, size))
    Element s;
    if(!e.hasRight(i, size))
    s = this.getLeft(i);
    else if(comp.compare(this.getLeft(i), this.getRight(i)) <= 0)
    s = this.getLeft(i);
    else
    s = this.getRight(i);
    if(comp.compare(s,e) < 0)
    swap(e,s);
    e = s;
    else
    break;
    public void swap(Element x, Element y)
    int temp = x.getIndex();
    x.setIndex(y.getIndex());
    y.setIndex(temp);
    public Element root() {return heap[0];}
    public Element getLeft(int i) {return heap[i*2];}
    public Element getRight(int i) {return heap[i*2+1];}
    public Element getParent(int i) {return heap[i/2];}
    class Element
    private int key;
    private int index;
    public Element(int k, int i)
    key = k;
    index = i;
    public int getKey() {return key;}
    public void setKey(int k) {key = k;}
    public int getIndex() {return index;}
    public void setIndex(int i) {index = i;}
    public boolean isRoot(int i) {
    if (i == 0)
    return true;
    else
    return false;
    //return i == 1;
    public boolean hasLeft(int i, int size) {return 2*i <= size;}
    public boolean hasRight(int i, int size) {return 2*i+1 <= size;}
    public boolean isInternal(int i, int size) {return hasLeft(i, size);}
    public boolean isExternal(int i, int size) {return !isInternal(i, size);}
    class Compare implements Comparator<Element>
    public Compare(){}
    public int compare(Element a, Element b)
    int x=0;
    if(a.getKey() < b.getKey())
    x = -1;
    else if(a.getKey() == b.getKey())
    x = 0;
    else if(a.getKey() > b.getKey())
    x = 1;
    return x;

    Well, this might be a swifty thing to do, unfortunately the Java Dudes in their infinite wisdom decided that asynchronous servlets were a bad thing. I disagree mind you. So while you could do what you wanted, you still have all these threads hangin' out waiting for their work to be done, which is just really lamo.
    Anyhoo, to do this, just add a reference to the socket in the entry class, and when you pick up an entry from the heap, you can fetch the socket again, and send the results back to that socket. Of course you're probably going to moof up session info, and timeouts et. cetera, but it might work.

  • Tutorial for make a non-generic type class from a generic type interface

    Hi there,
    How can I make a non-generic type class from a generic type interface?
    I appreciate if somebody let me know which site can help me.
    Regards
    Maurice

    I have a generic interface with this signature
    public interface IELO<K extends IMetadataKey>
    and I have implemented a class from it
    public class CmsELOImpl<K extends IMetadataKey> implements IELO<K>, Cloneable, Serializable
    then I have to pass class of an instance CmsELOImpl to AbstractJcrDAO class constructor whit below signature
    public abstract class AbstractJcrDAO<T> implements JcrDAO<T> {
    public AbstractJcrDAO( Class<T> entityClass, Session session, Jcrom jcrom ) {
              this(entityClass, session, jcrom, new String[0]);
    So I have made another class extended from AbstractJcrDAO. Below shows the code of this class and itd constructor
    public class ELODaoImpl extends AbstractJcrDAO<CmsELOImpl<IMetadataKey>> {
         public ELODaoImpl( Session session, Jcrom jcrom ) {
         super(CmsELOImpl.class , session , jcrom, MIXIN_TYPES);
    and as you see in its constructor I am calling the AbstractJcrDAO constructor by supper method
    then I got this error on the line of super method
    The constructor AbstractJcrDAO(class<CmsELOImpl>, session, Jcrom, String[]) is undefined.
    as I know java generics are implemented using type erasure. This generics are only
    in the java source file and not in the class files. The generics are only used by the compiler and
    they are erased from the class files. This is done to make generics compatible with (old) non generics java code.
    As a result the class object of AbstractJcrDAO<CmsELOImpl<IMetadataKey>>
    is AbstractJcrDAO.class. The <CmsELOImpl<IMetadataKey>> information is
    not available in the class file. As far as I understand it, I am looking a way
    to pass <CmsELOImpl<IMetadataKey>>, if it is possible at all.
    Maurice

  • Urgent!!!!!!!!!!  How do I compare?????

    How do I compare two PatrickSwayze objects?
    For example, is it even possible to make the following comparisons?
    if (PatrickSwayze.Roadhouse.equals(PatrickSwayze.ToWongFooThanksForEverythingJulieNewmar)
    {...}or
    if (PatrickSwayze.PointBreak.equals(PatrickSwayze.RedDawn)
    {...}

    TEST FOR EQUALITY -- overwrite the equals(). This returns TRUE or FALSE and can be used.anywhere a boolean value is needed.
    COMPARE - implement java.lang.Comparable and include the compareTo() method. This returns an int value of -1, 0, or 1. Then you can use these values in a sorting algorithm or any other kind of ordering system.
    To the author: In your IF statement, you are using a TEST FOR EQUALITY, even though you are calling it a COMPARISON. Think about these definitions clearly... they are often used interchangabley, but they are not the same.

  • Generics and creating new objects

    Assume this class:
    class Yatta<T>
      public Yatta()
        T t = new T();
    }When compiling I get "unexpected type" refering to the "T" in "new T()". Why isn't this allowed? Is there any way of doing something similar without creating a huge chain of factories for each type?

    Please use single letters for type parameters. Doing what you've done with "Type" makes reading the code difficult...
    Since duplicate() is declared in Component I assume it is declared to return Component. How can the compiler possibly know that it is going to return a more specific type? It can't. (Well... you can tell it... see below)
    Because of what I wrote in the first paragraph, it's not immediately obvious that Type is a type parameter, but it is, and casting to a type parameter doesn't get you anywhere. From this code and your original post, you appear to be treating Java Generics like C++ templates. They are not the same. In particular, Generics are implemented using a technique called erasure which means that the type parameter information is not present in the compiled class files. The practical upshot of this is that the cast in the line you highlight is in fact a cast to Component (since that is the upper bound of Type) and this cast is useless because we already know the c is a Component. So the compiler is correctly warning you that the typecast will not actually perform the check that you want it to.
    (In fact, if you try this in Eclipse, you get a better warning: "Type safety: The cast from Component to T is actually checking against the erased type Component")
    So... how to fix this...?
    Well, you need to make the return type of duplicate() change depending on the concrete implementation. You could do this by parameterising Component thus:
      public interface Component<T extends Component<T>> {
        public T duplicate();
      }Now, every use of Component will need to be parameterised. In the case of the code you have below, you'll need:
    public class Container<T extends Component<T>> extends ArrayList<T> {
      public Container() {
        //Empty
        // Why write it then??? Get rid of it.
      public Container(Container<T> object) {
        Iterator<T> i = object.iterator();  // don't need ListIterator here
        while(i.hasNext()) {
          add(i.next().duplicate());
    }and every implementation of Component needs to look like this:
    public static class Something implements Component<Something> {
      public Something duplicate() {  // note the return type
        return null;  // or something more useful!
    }Hope that helps.
    (PS 'tabs' are the work of satan and should never be found in source code)

  • The behavior of comparator

    Hi
    How do the following codes produce different results? (Both are part of a Comparator implementation)
    public final int compare ( Object a, Object b )
                return( (Comparable)a ).compareTo( b );
    public final int compare ( Object a, Object b )
          // reverse the usual roles of a and b
          return( (Comparable)b ).compareTo( a );
       }Actually how do the caller of the comparator method utilize the return value?
    I mean say the list is {5,4,....}
    so a = 5, b = 4
    In the first case, a<b so the return value is negative. and for the second case b>a so the return value is positive.
    If the caller wants to put negative values first and positive values next, then in both cases a should come before b. No where in the comparator I have mentioned that In the first case I want to put negative values first and in the second case positive values first.
    So please somebody clarify the things.

    amishera2006 wrote:
    Actually how do the caller of the comparator method utilize the return value? When you're using Comparable, try to think of compareTo as determining whether something is absolutely greater or less than something else, NOT whether it is before or after something else. Typically, when you use Comparable, it's because two things can be compared in such a way. For instance, it's natural to say that a date in the year 1900 happened before a date in the year 2000. Dates have a natural ordering. It wouldn't be natural to say that two cars have an intrinsic, deferential and natural ordering, so implementing Comparable for a class "Car" wouldn't make much sense.
    When you see this, you also see that compareTo should return the same thing, no matter if you are trying to sort forward or in reverse. According to the Javadoc, compareTo() "Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object" -- not depending on how you choose to sort your objects.
    To sort backwards you'd just create a Comparator like in your second example.

Maybe you are looking for