Search Results

Search found 196 results on 8 pages for 'compareto'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • using compareTo in Binary Search Tree program

    - by Scott Rogener
    I've been working on this program for a few days now and I've implemented a few of the primary methods in my BinarySearchTree class such as insert and delete. Insert seemed to be working fine, but once I try to delete I kept getting errors. So after playing around with the code I wanted to test my compareTo methods. I created two new nodes and tried to compare them and I get this error: Exception in thread "main" java.lang.ClassCastException: TreeNode cannot be cast to java.lang.Integer at java.lang.Integer.compareTo(Unknown Source) at TreeNode.compareTo(TreeNode.java:16) at BinarySearchTree.myComparision(BinarySearchTree.java:177) at main.main(main.java:14) Here is my class for creating the nodes: public class TreeNode<T> implements Comparable { protected TreeNode<T> left, right; protected Object element; public TreeNode(Object obj) { element=obj; left=null; right=null; } public int compareTo(Object node) { return ((Comparable) this.element).compareTo(node); } } Am I doing the compareTo method all wrong? I would like to create trees that can handle integers and strings (seperatly of course)

    Read the article

  • How to CompareTo two Object without known about their real type

    - by Kamil
    I have to implement a one linked list but it should put object in appropriate position. Everything was OK when I use it in conjunction with specific class, but when I tried make it universal and argument of method insert was Object some problem appeared. When I want to input Object in right position I should use CompareTo method, but there isn't method in Object class! The problem is how to compare two object elements without known about their real types. Maybe I should use generic class type? But what about CompareTo? Or maybe combine with Element class and place CompareTo there? I suppose it is feasible. :) public void insert(Object o) { Element el = new Element(o); // initializing and setting iterators while(!it.isDone() && ((it.current().getValue())).CompareTo(o)<0) // it.current() returns Element of List { //move interators } //... }

    Read the article

  • How do I sort an array of Person Objects by using compareto()?

    - by Adam
    Here is my code: > import java.util.Scanner; import java.util.Arrays; /** This class tests the Person class. */ public class PersonDemo { public static void main(String[] args) { int count = 0; Scanner in = new Scanner(System.in); boolean more = false; Person first = null; Person last = null; while (more) { System.out.println( "Please enter the person's name or a blank line to quit"); String name = in.nextLine(); if (name.equals("")) more = false; else { Person p = new Person(name); //new person object created with inputted name Person[] people = new Person[10]; //new array of 10 person objects people[count] = p; //declare person object with index of variable count as the new person object first = people[count]; // I have no idea what to do here. This is where I'm stuck. last = people[count]; // I can't figure out what to do with this either. first.compareTo(p); //call compareTo method on first and new person object last.compareTo(p); //call compareTo method on last and new person object count++; // increase count variable } } System.out.println("First: " + first.toString()); System.out.println("Last: " + last.toString()); } } And the Person class: /** A person with a name. */ public class Person implements Comparable { /** * Constructs a Person with a name. * @param aName the person's name */ public Person(String aName) { name = aName; } public String getName() { return name; } @Override public int compareTo(Object otherObject) { Person other = (Person)otherObject; if (name.compareTo(other.name) < 0) return -1; if (name.compareTo(other.name) > 0) return 1; return 0; } /** Returns a string representation of the object. @return name of Person */ public String toString() { return "[name=" + name + "]"; } private String name; }

    Read the article

  • Does the specific signed integer matter when implementing compareTo in a Comparable <Type> class?

    - by javanix
    When implementing compareTo(), does the degree of "difference" need to be taken into account? For instance, if I have 3 objects, C1, C2, and C3, such that C1 < C2 < C3. Should C1.compareTo(C2) return an integer that is less than C2.compareTo(C3)? The documentation for the Comparable interface doesn't seem to specify one way or another, so I'm guessing the degree doesn't matter, but it would be nice to know if there is some advantage returning a specific number (for example, improving TreeSet sort speed or something). http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html#compareTo(T)

    Read the article

  • Using CompareTo() on different .NET types (e.g. int vs. double)

    - by Yossin
    Hi, I've got a static method that accepts two object type variables and runs the CompareTo() method: public static int Compare(Object objA, Object objB) { return (((IComparable)objA).CompareTo(objB)); } Problem is that CompareTo() throws an exception when trying to compare between different types (e.g. int and double). Does any one know of a better way in C#, to compare between two different types? Or a workaround to this problem? Thanks

    Read the article

  • C#/Java: Proper Implementation of CompareTo when Equals tests reference identity

    - by Paul A Jungwirth
    I believe this question applies equally well to C# as to Java, because both require that {c,C}ompareTo be consistent with {e,E}quals: Suppose I want my equals() method to be the same as a reference check, i.e.: public bool equals(Object o) { return this == o; } In that case, how do I implement compareTo(Object o) (or its generic equivalent)? Part of it is easy, but I'm not sure about the other part: public int compareTo(Object o) { if (! (o instanceof MyClass)) return false; MyClass other = (MyClass)o; if (this == other) { return 0; } else { int c = foo.CompareTo(other.foo) if (c == 0) { // what here? } else { return c; } } } I can't just blindly return 1 or -1, because the solution should adhere to the normal requirements of compareTo. I can check all the instance fields, but if they are all equal, I'd still like compareTo to return a value other than 0. It should be true that a.compareTo(b) == -(b.compareTo(a)), and the ordering should stay consistent as long as the objects' state doesn't change. I don't care about ordering across invocations of the virtual machine, however. This makes me think that I could use something like memory address, if I could get at it. Then again, maybe that won't work, because the Garbage Collector could decide to move my objects around. hashCode is another idea, but I'd like something that will be always unique, not just mostly unique. Any ideas?

    Read the article

  • FindBugs - how to solve EQ_COMPARETO_USE_OBJECT_EQUALS

    - by Trick
    I am clueless here... 1: private static class ForeignKeyConstraint implements Comparable<ForeignKeyConstraint> { 2: String tableName; 3: String fkFieldName; 4: 5: public int compareTo(ForeignKeyConstraint o) { 6: if (this.tableName.compareTo(o.tableName) == 0) { 7: return this.fkFieldName.compareTo(o.fkFieldName); 8: } 9: return this.tableName.compareTo(o.tableName); 10: } 11: } In line 6 I get from FindBugs: Bug: net.blabla.SqlFixer$ForeignKeyConstraint defines compareTo(SqlFixer$ForeignKeyConstraint) and uses Object.equals() Link to definition I don't know how to correct this :S

    Read the article

  • compareTo() method java is acting weird

    - by Ron Paul
    hi im having trouble getting this to work im getting an error here with my object comparison...how could I cast the inches to a string ( i never used compare to with anything other than strings) , or use comparison operators to compare the intigers, Object comparison = this.inches.compareTo(obj.inches); here is my code so far import java.io.*; import java.util.*; import java.lang.Integer; import java.lang.reflect.Array; public class Distance implements Comparable<Distance> { private static final String HashCodeUtil = null; private int feet; private int inches; private final int DEFAULT_FT = 1; private final int DEFAULT_IN = 1; public Distance(){ feet = DEFAULT_FT; inches = DEFAULT_IN; } public Distance(int ft, int in){ feet = ft; inches = in; } public void setFeet(int ft){ try { if(ft<0){ throw new CustomException("Distance is not negative"); } } catch(CustomException c){ System.err.println(c); feet =ft; } } public int getFeet(){ return feet; } public void setInches(int in){ try { if (in<0) throw new CustomException("Distance is not negative"); //inches = in; } catch(CustomException c) { System.err.println(c); inches = in; } } public int getInches(){ return inches; } public String toString (){ return "<" + feet + ":" + inches + ">"; } public Distance add(Distance m){ Distance n = new Distance(); n.inches = this.inches + m.inches; n.feet = this.feet + m.feet; while(n.inches>12){ n.inches = n.inches - 12; n.feet++; } return n; } public Distance subtract(Distance f){ Distance m = new Distance(); m.inches = this.inches - f.inches; m.feet = this.feet - f.feet; while(m.inches<0){ m.inches = m.inches - 12; feet--; } return m; } @Override public int compareTo(Distance obj) { // TODO Auto-generated method stub final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; if (this == obj) return EQUAL; if(this.DEFAULT_IN < obj.DEFAULT_FT) return BEFORE; if(this.DEFAULT_IN > obj.DEFAULT_FT) return AFTER; Object comparison = this.inches.compareTo(obj.inches); if (this.inches == obj.inches) return compareTo(null); assert this.equals(obj) : "compareTo inconsistent with equals"; return EQUAL; } @Override public boolean equals( Object obj){ if (obj != null) return false; if (!(obj intanceof Distance)) return false; Distance that = (Distance)obj; ( this.feet == that.feet && this.inches == that.inches); return true; else return false; } @Override public int hashCode(int, int) { int result = HashCodeUtil.inches; result = HashCodeUtil.hash(result, inches ); result = HashCodeUtil.hash(result, feet); ruturn result; }

    Read the article

  • compareTo and nested Enums

    - by echox
    Hi, in "A Programmers Guide to Java SCJP Certification" I found an example which I can't follow. This the given enum: enum Scale3 { GOOD(Grade.C), BETTER(Grade.B), BEST(Grade.A); enum Grade {A, B, C} private Grade grade; Scale3(Grade grade) { this.grade = grade; } public Grade getGrade() { return grade; } } This is the given expression: Scale3.GOOD.getGrade().compareTo(Scale3.Grade.A) > 0; I don't understand why this expression will be true? The return value will be 2. compareTo() will return a value 0 if the given object is "less" than the object. Scale3.Grade.A is the "biggest" element of Grades, its ordinal number is 0. Scale3.GOOD is the "biggest" element of Scale3, its ordinal number is also 0. The constructor of Scale3 is called with Scale3.Grade.C, which ordinal number is 2. So the given expression is equal to the following code: Scale3.Grade.C.compareTo(Scale3.Grade.A) > 0; A is "bigger" than C, so shouldn't be the result < 0?

    Read the article

  • Python equivalent of Java's compareTo()

    - by astay13
    I'm doing a project in Python (3.2) for which I need to compare user defined objects. I'm used to OOP in Java, where one would define a compareTo() method in the class that specifies the natural ordering of that class, as in the example below: public class Foo { int a, b; public Foo(int aa, int bb) { a = aa; b = bb; } public int compareTo(Foo that) { // return a negative number if this < that // return 0 if this == that // return a positive number if this > that if (this.a == that.a) return this.b - that.b; else return this.a - that.a; } } I'm fairly new to classes/objects in Python, so I'd like to know what is the "pythonic" way to define the natural ordering of a class?

    Read the article

  • Unchecked call to compareTo

    - by Dave Jarvis
    Background Create a Map that can be sorted by value. Problem The code executes as expected, but does not compile cleanly: http://pastebin.com/bWhbHQmT The syntax for passing Comparable as a generic parameter along to the Map.Entry<K, V> (where V must be Comparable?) -- so that the (Comparable) typecast shown in the warning can be dropped -- eludes me. Warning Compiler's cantankerous complaint: SortableValueMap.java:24: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() ); Question How can the code be changed to compile without any warnings (without suppressing them while compiling with -Xlint:unchecked)? Related TreeMap sort by value How to sort a Map on the values in Java? http://paaloliver.wordpress.com/2006/01/24/sorting-maps-in-java/ Thank you!

    Read the article

  • How to make compareTo sort a list alphabetically?

    - by Alex
    Hi How do I change my code so that it lists the elements in alphabetical order from a to z. Right now it's ordering from z to a. I can't figure it out and am stuck :-/ String sName1 = ((Address)o).getSurname().toLowerCase(); String sName2 = (this.surname).toLowerCase(); int result = (sName1).compareTo(sName2); return result; Thanks :)

    Read the article

  • 2 compareTo method overriden in the same class definition, how could I force to use the second?

    - by jayjaypg22
    I want to sort a list List<Blabla> donnees by a criterion on one of its field. My problem is that compareTo is already overriden for this Class. So I've got something like : Blabla { public int compareTo(Object other) { ... } public int compareTo(Blabla other) { ... } } In a business layer class I call : Business { method (){ Collections.sort(List<Blabla > donnees); } } But this call N°1 compareTo method with object parameter. How could I sort my list with the N°2 method?

    Read the article

  • Why does Ordered[A] use a compare method instead of reusing compareTo?

    - by soc
    trait Ordered[A] extends java.lang.Comparable[A] { def compare(that: A): Int def < (that: A): Boolean = (this compare that) < 0 def > (that: A): Boolean = (this compare that) > 0 def <= (that: A): Boolean = (this compare that) <= 0 def >= (that: A): Boolean = (this compare that) >= 0 def compareTo(that: A): Int = compare(that) } Isn't it a bit useless to have both compare and compareTo? What is the huge benefit I'm missing here? If they had just used compareTo I could just had replaced Comparable with Ordered in my code and be done.

    Read the article

  • Entity Framework 4.0 and DDD patterns

    - by Voice
    Hi everybody I use EntityFramework as ORM and I have simple POCO Domain Model with two base classes that represent Value Object and Entity Object Patterns (Evans). These two patterns is all about equality of two objects, so I overrode Equals and GetHashCode methods. Here are these two classes: public abstract class EntityObject<T>{ protected T _ID = default(T); public T ID { get { return _ID; } protected set { _ID = value; } } public sealed override bool Equals(object obj) { EntityObject<T> compareTo = obj as EntityObject<T>; return (compareTo != null) && ((HasSameNonDefaultIdAs(compareTo) || (IsTransient && compareTo.IsTransient)) && HasSameBusinessSignatureAs(compareTo)); } public virtual void MakeTransient() { _ID = default(T); } public bool IsTransient { get { return _ID == null || _ID.Equals(default(T)); } } public override int GetHashCode() { if (default(T).Equals(_ID)) return 0; return _ID.GetHashCode(); } private bool HasSameBusinessSignatureAs(EntityObject<T> compareTo) { return ToString().Equals(compareTo.ToString()); } private bool HasSameNonDefaultIdAs(EntityObject<T> compareTo) { return (_ID != null && !_ID.Equals(default(T))) && (compareTo._ID != null && !compareTo._ID.Equals(default(T))) && _ID.Equals(compareTo._ID); } public override string ToString() { StringBuilder str = new StringBuilder(); str.Append(" Class: ").Append(GetType().FullName); if (!IsTransient) str.Append(" ID: " + _ID); return str.ToString(); } } public abstract class ValueObject<T, U> : IEquatable<T> where T : ValueObject<T, U> { private static List<PropertyInfo> Properties { get; set; } private static Func<ValueObject<T, U>, PropertyInfo, object[], object> _GetPropValue; static ValueObject() { Properties = new List<PropertyInfo>(); var propParam = Expression.Parameter(typeof(PropertyInfo), "propParam"); var target = Expression.Parameter(typeof(ValueObject<T, U>), "target"); var indexPar = Expression.Parameter(typeof(object[]), "indexPar"); var call = Expression.Call(propParam, typeof(PropertyInfo).GetMethod("GetValue", new[] { typeof(object), typeof(object[]) }), new[] { target, indexPar }); var lambda = Expression.Lambda<Func<ValueObject<T, U>, PropertyInfo, object[], object>>(call, target, propParam, indexPar); _GetPropValue = lambda.Compile(); } public U ID { get; protected set; } public override Boolean Equals(Object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != GetType()) return false; return Equals(obj as T); } public Boolean Equals(T other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; foreach (var property in Properties) { var oneValue = _GetPropValue(this, property, null); var otherValue = _GetPropValue(other, property, null); if (null == oneValue && null == otherValue) return false; if (false == oneValue.Equals(otherValue)) return false; } return true; } public override Int32 GetHashCode() { var hashCode = 36; foreach (var property in Properties) { var propertyValue = _GetPropValue(this, property, null); if (null == propertyValue) continue; hashCode = hashCode ^ propertyValue.GetHashCode(); } return hashCode; } public override String ToString() { var stringBuilder = new StringBuilder(); foreach (var property in Properties) { var propertyValue = _GetPropValue(this, property, null); if (null == propertyValue) continue; stringBuilder.Append(propertyValue.ToString()); } return stringBuilder.ToString(); } protected static void RegisterProperty(Expression<Func<T, Object>> expression) { MemberExpression memberExpression; if (ExpressionType.Convert == expression.Body.NodeType) { var body = (UnaryExpression)expression.Body; memberExpression = body.Operand as MemberExpression; } else memberExpression = expression.Body as MemberExpression; if (null == memberExpression) throw new InvalidOperationException("InvalidMemberExpression"); Properties.Add(memberExpression.Member as PropertyInfo); } } Everything was OK until I tried to delete some related objects (aggregate root object with two dependent objects which was marked for cascade deletion): I've got an exception "The relationship could not be changed because one or more of the foreign-key properties is non-nullable". I googled this and found http://blog.abodit.com/2010/05/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-properties-is-non-nullable/ I changed GetHashCode to base.GetHashCode() and error disappeared. But now it breaks all my code: I can't override GetHashCode for my POCO objects = I can't override Equals = I can't implement Value Object and Entity Object patters for my POCO objects. So, I appreciate any solutions, workarounds here etc.

    Read the article

  • C#/.NET Little Wonders: Comparer&lt;T&gt;.Default

    - by James Michael Hare
    I’ve been working with a wonderful team on a major release where I work, which has had the side-effect of occupying most of my spare time preparing, testing, and monitoring.  However, I do have this Little Wonder tidbit to offer today. Introduction The IComparable<T> interface is great for implementing a natural order for a data type.  It’s a very simple interface with a single method: 1: public interface IComparer<in T> 2: { 3: // Compare two instances of same type. 4: int Compare(T x, T y); 5: }  So what do we expect for the integer return value?  It’s a pseudo-relative measure of the ordering of x and y, which returns an integer value in much the same way C++ returns an integer result from the strcmp() c-style string comparison function: If x == y, returns 0. If x > y, returns > 0 (often +1, but not guaranteed) If x < y, returns < 0 (often –1, but not guaranteed) Notice that the comparison operator used to evaluate against zero should be the same comparison operator you’d use as the comparison operator between x and y.  That is, if you want to see if x > y you’d see if the result > 0. The Problem: Comparing With null Can Be Messy This gets tricky though when you have null arguments.  According to the MSDN, a null value should be considered equal to a null value, and a null value should be less than a non-null value.  So taking this into account we’d expect this instead: If x == y (or both null), return 0. If x > y (or y only is null), return > 0. If x < y (or x only is null), return < 0. But here’s the problem – if x is null, what happens when we attempt to call CompareTo() off of x? 1: // what happens if x is null? 2: x.CompareTo(y); It’s pretty obvious we’ll get a NullReferenceException here.  Now, we could guard against this before calling CompareTo(): 1: int result; 2:  3: // first check to see if lhs is null. 4: if (x == null) 5: { 6: // if lhs null, check rhs to decide on return value. 7: if (y == null) 8: { 9: result = 0; 10: } 11: else 12: { 13: result = -1; 14: } 15: } 16: else 17: { 18: // CompareTo() should handle a null y correctly and return > 0 if so. 19: result = x.CompareTo(y); 20: } Of course, we could shorten this with the ternary operator (?:), but even then it’s ugly repetitive code: 1: int result = (x == null) 2: ? ((y == null) ? 0 : -1) 3: : x.CompareTo(y); Fortunately, the null issues can be cleaned up by drafting in an external Comparer.  The Soltuion: Comparer<T>.Default You can always develop your own instance of IComparer<T> for the job of comparing two items of the same type.  The nice thing about a IComparer is its is independent of the things you are comparing, so this makes it great for comparing in an alternative order to the natural order of items, or when one or both of the items may be null. 1: public class NullableIntComparer : IComparer<int?> 2: { 3: public int Compare(int? x, int? y) 4: { 5: return (x == null) 6: ? ((y == null) ? 0 : -1) 7: : x.Value.CompareTo(y); 8: } 9: }  Now, if you want a custom sort -- especially on large-grained objects with different possible sort fields -- this is the best option you have.  But if you just want to take advantage of the natural ordering of the type, there is an easier way.  If the type you want to compare already implements IComparable<T> or if the type is System.Nullable<T> where T implements IComparable, there is a class in the System.Collections.Generic namespace called Comparer<T> which exposes a property called Default that will create a singleton that represents the default comparer for items of that type.  For example: 1: // compares integers 2: var intComparer = Comparer<int>.Default; 3:  4: // compares DateTime values 5: var dateTimeComparer = Comparer<DateTime>.Default; 6:  7: // compares nullable doubles using the null rules! 8: var nullableDoubleComparer = Comparer<double?>.Default;  This helps you avoid having to remember the messy null logic and makes it to compare objects where you don’t know if one or more of the values is null. This works especially well when creating say an IComparer<T> implementation for a large-grained class that may or may not contain a field.  For example, let’s say you want to create a sorting comparer for a stock open price, but if the market the stock is trading in hasn’t opened yet, the open price will be null.  We could handle this (assuming a reasonable Quote definition) like: 1: public class Quote 2: { 3: // the opening price of the symbol quoted 4: public double? Open { get; set; } 5:  6: // ticker symbol 7: public string Symbol { get; set; } 8:  9: // etc. 10: } 11:  12: public class OpenPriceQuoteComparer : IComparer<Quote> 13: { 14: // Compares two quotes by opening price 15: public int Compare(Quote x, Quote y) 16: { 17: return Comparer<double?>.Default.Compare(x.Open, y.Open); 18: } 19: } Summary Defining a custom comparer is often needed for non-natural ordering or defining alternative orderings, but when you just want to compare two items that are IComparable<T> and account for null behavior, you can use the Comparer<T>.Default comparer generator and you’ll never have to worry about correct null value sorting again.     Technorati Tags: C#,.NET,Little Wonders,BlackRabbitCoder,IComparable,Comparer

    Read the article

  • How can I make my generic comparer (IComparer) handle nulls? [closed]

    - by Nick G
    Hi, I'm trying to write a generic object comparer for sorting, but I have noticed it does not handle the instance where one of the values it's comparing is null. When an object is null, I want it to treat it the same as the empty string. I've tried setting the null values to String.Empty but then I get an error of "Object must be of type String" when calling CompareTo() on it. public int Compare(T x, T y) { PropertyInfo propertyInfo = typeof(T).GetProperty(sortExpression); IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null); IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null); if (obj1 == null) obj1 = String.Empty; // This doesn't work! if (obj2 == null) obj2 = String.Empty; // This doesn't work! if (SortDirection == SortDirection.Ascending) return obj1.CompareTo(obj2); else return obj2.CompareTo(obj1); } I'm pretty stuck with this now! Any help would be appreciated.

    Read the article

  • C#: IComparable implementation private

    - by Anonymous Coward
    Hello I'm new to C# so this might be a really dump question: I implemented IComparable in my class and want to test it with NUnit. But the CompareTo-Method is marked as private and thus not accessible from the test. What's the reason for this and how can I fix this? The IComparable: public class PersonHistoryItem : DateEntity,IComparable { ... int IComparable.CompareTo(object obj) { PersonHistoryItem phi = (PersonHistoryItem)obj; return this.StartDate.CompareTo(phi.StartDate); } } The test: [TestMethod] public void TestPersonHistoryItem() { DateTime startDate = new DateTime(2001, 2, 2); DateTime endDate = new DateTime(2010, 2, 2); PersonHistoryItem phi1 = new PersonHistoryItem(startDate,endDate); PersonHistoryItem phi2 = new PersonHistoryItem(startDate, endDate); Assert.IsTrue(phi1.CompareTo(phi2)==0); }

    Read the article

  • Generic Constraints And Type Parameters Mess

    - by Dummy01
    Hi everyone, I have the following base abstract class defined as: public abstract class BaseObject<T> : IComparable, IComparable<T>, IEquatable<T> {} I also have an interface defined as: public interface ICode<T> where T : struct { T Code { get; } } Now I want to derive a class that is inherited from BaseObject<T> and includes interface ICode<T>. I tried to define it like that: public class DerivedObject<T, U> : BaseObject<T>, ICode<U> where T : DerivedObject<T, U> where U : struct { public DerivedObject(U code) { Code = code; } // From BaseObject protected override int InstanceCompareTo(T obj) { return Code.CompareTo(obj.Code); } // From BaseObject protected override bool InstanceEquals(T obj) { return Code.Equals(obj.Code); } // From ICode U _Code; public U Code { get { return _Code; } protected set { _Code = value; } } } The only error that comes from the compiler is for Code.CompareTo(obj.Code) with the message: 'U' does not contain a definition for 'CompareTo' and no extension method 'CompareTo' accepting a first argument of type 'U' could be found. But U is a value type and should know CompareTo. Have you any idea what I am doing wrong, or if I do all wrong? My final aim is to derive classes such these: public class Account : DerivedObject<Account, int> public class ItemGroup : DerivedObject<ItemGroup, string> Big Thanks In Advance!

    Read the article

  • How to simulate inner join on very large files in java (without running out of memory)

    - by Constantin
    I am trying to simulate SQL joins using java and very large text files (INNER, RIGHT OUTER and LEFT OUTER). The files have already been sorted using an external sort routine. The issue I have is I am trying to find the most efficient way to deal with the INNER join part of the algorithm. Right now I am using two Lists to store the lines that have the same key and iterate through the set of lines in the right file once for every line in the left file (provided the keys still match). In other words, the join key is not unique in each file so would need to account for the Cartesian product situations ... left_01, 1 left_02, 1 right_01, 1 right_02, 1 right_03, 1 left_01 joins to right_01 using key 1 left_01 joins to right_02 using key 1 left_01 joins to right_03 using key 1 left_02 joins to right_01 using key 1 left_02 joins to right_02 using key 1 left_02 joins to right_03 using key 1 My concern is one of memory. I will run out of memory if i use the approach below but still want the inner join part to work fairly quickly. What is the best approach to deal with the INNER join part keeping in mind that these files may potentially be huge public class Joiner { private void join(BufferedReader left, BufferedReader right, BufferedWriter output) throws Throwable { BufferedReader _left = left; BufferedReader _right = right; BufferedWriter _output = output; Record _leftRecord; Record _rightRecord; _leftRecord = read(_left); _rightRecord = read(_right); while( _leftRecord != null && _rightRecord != null ) { if( _leftRecord.getKey() < _rightRecord.getKey() ) { write(_output, _leftRecord, null); _leftRecord = read(_left); } else if( _leftRecord.getKey() > _rightRecord.getKey() ) { write(_output, null, _rightRecord); _rightRecord = read(_right); } else { List<Record> leftList = new ArrayList<Record>(); List<Record> rightList = new ArrayList<Record>(); _leftRecord = readRecords(leftList, _leftRecord, _left); _rightRecord = readRecords(rightList, _rightRecord, _right); for( Record equalKeyLeftRecord : leftList ){ for( Record equalKeyRightRecord : rightList ){ write(_output, equalKeyLeftRecord, equalKeyRightRecord); } } } } if( _leftRecord != null ) { write(_output, _leftRecord, null); _leftRecord = read(_left); while(_leftRecord != null) { write(_output, _leftRecord, null); _leftRecord = read(_left); } } else { if( _rightRecord != null ) { write(_output, null, _rightRecord); _rightRecord = read(_right); while(_rightRecord != null) { write(_output, null, _rightRecord); _rightRecord = read(_right); } } } _left.close(); _right.close(); _output.flush(); _output.close(); } private Record read(BufferedReader reader) throws Throwable { Record record = null; String data = reader.readLine(); if( data != null ) { record = new Record(data.split("\t")); } return record; } private Record readRecords(List<Record> list, Record record, BufferedReader reader) throws Throwable { int key = record.getKey(); list.add(record); record = read(reader); while( record != null && record.getKey() == key) { list.add(record); record = read(reader); } return record; } private void write(BufferedWriter writer, Record left, Record right) throws Throwable { String leftKey = (left == null ? "null" : Integer.toString(left.getKey())); String leftData = (left == null ? "null" : left.getData()); String rightKey = (right == null ? "null" : Integer.toString(right.getKey())); String rightData = (right == null ? "null" : right.getData()); writer.write("[" + leftKey + "][" + leftData + "][" + rightKey + "][" + rightData + "]\n"); } public static void main(String[] args) { try { BufferedReader leftReader = new BufferedReader(new FileReader("LEFT.DAT")); BufferedReader rightReader = new BufferedReader(new FileReader("RIGHT.DAT")); BufferedWriter output = new BufferedWriter(new FileWriter("OUTPUT.DAT")); Joiner joiner = new Joiner(); joiner.join(leftReader, rightReader, output); } catch (Throwable e) { e.printStackTrace(); } } } After applying the ideas from the proposed answer, I changed the loop to this private void join(RandomAccessFile left, RandomAccessFile right, BufferedWriter output) throws Throwable { long _pointer = 0; RandomAccessFile _left = left; RandomAccessFile _right = right; BufferedWriter _output = output; Record _leftRecord; Record _rightRecord; _leftRecord = read(_left); _rightRecord = read(_right); while( _leftRecord != null && _rightRecord != null ) { if( _leftRecord.getKey() < _rightRecord.getKey() ) { write(_output, _leftRecord, null); _leftRecord = read(_left); } else if( _leftRecord.getKey() > _rightRecord.getKey() ) { write(_output, null, _rightRecord); _pointer = _right.getFilePointer(); _rightRecord = read(_right); } else { long _tempPointer = 0; int key = _leftRecord.getKey(); while( _leftRecord != null && _leftRecord.getKey() == key ) { _right.seek(_pointer); _rightRecord = read(_right); while( _rightRecord != null && _rightRecord.getKey() == key ) { write(_output, _leftRecord, _rightRecord ); _tempPointer = _right.getFilePointer(); _rightRecord = read(_right); } _leftRecord = read(_left); } _pointer = _tempPointer; } } if( _leftRecord != null ) { write(_output, _leftRecord, null); _leftRecord = read(_left); while(_leftRecord != null) { write(_output, _leftRecord, null); _leftRecord = read(_left); } } else { if( _rightRecord != null ) { write(_output, null, _rightRecord); _rightRecord = read(_right); while(_rightRecord != null) { write(_output, null, _rightRecord); _rightRecord = read(_right); } } } _left.close(); _right.close(); _output.flush(); _output.close(); } UPDATE While this approach worked, it was terribly slow and so I have modified this to create files as buffers and this works very well. Here is the update ... private long getMaxBufferedLines(File file) throws Throwable { long freeBytes = Runtime.getRuntime().freeMemory() / 2; return (freeBytes / (file.length() / getLineCount(file))); } private void join(File left, File right, File output, JoinType joinType) throws Throwable { BufferedReader leftFile = new BufferedReader(new FileReader(left)); BufferedReader rightFile = new BufferedReader(new FileReader(right)); BufferedWriter outputFile = new BufferedWriter(new FileWriter(output)); long maxBufferedLines = getMaxBufferedLines(right); Record leftRecord; Record rightRecord; leftRecord = read(leftFile); rightRecord = read(rightFile); while( leftRecord != null && rightRecord != null ) { if( leftRecord.getKey().compareTo(rightRecord.getKey()) < 0) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.LeftExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, leftRecord, null); } leftRecord = read(leftFile); } else if( leftRecord.getKey().compareTo(rightRecord.getKey()) > 0 ) { if( joinType == JoinType.RightOuterJoin || joinType == JoinType.RightExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, null, rightRecord); } rightRecord = read(rightFile); } else if( leftRecord.getKey().compareTo(rightRecord.getKey()) == 0 ) { String key = leftRecord.getKey(); List<File> rightRecordFileList = new ArrayList<File>(); List<Record> rightRecordList = new ArrayList<Record>(); rightRecordList.add(rightRecord); rightRecord = consume(key, rightFile, rightRecordList, rightRecordFileList, maxBufferedLines); while( leftRecord != null && leftRecord.getKey().compareTo(key) == 0 ) { processRightRecords(outputFile, leftRecord, rightRecordFileList, rightRecordList, joinType); leftRecord = read(leftFile); } // need a dispose for deleting files in list } else { throw new Exception("DATA IS NOT SORTED"); } } if( leftRecord != null ) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.LeftExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, leftRecord, null); } leftRecord = read(leftFile); while(leftRecord != null) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.LeftExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, leftRecord, null); } leftRecord = read(leftFile); } } else { if( rightRecord != null ) { if( joinType == JoinType.RightOuterJoin || joinType == JoinType.RightExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, null, rightRecord); } rightRecord = read(rightFile); while(rightRecord != null) { if( joinType == JoinType.RightOuterJoin || joinType == JoinType.RightExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, null, rightRecord); } rightRecord = read(rightFile); } } } leftFile.close(); rightFile.close(); outputFile.flush(); outputFile.close(); } public void processRightRecords(BufferedWriter outputFile, Record leftRecord, List<File> rightFiles, List<Record> rightRecords, JoinType joinType) throws Throwable { for(File rightFile : rightFiles) { BufferedReader rightReader = new BufferedReader(new FileReader(rightFile)); Record rightRecord = read(rightReader); while(rightRecord != null){ if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.RightOuterJoin || joinType == JoinType.FullOuterJoin || joinType == JoinType.InnerJoin ) { write(outputFile, leftRecord, rightRecord); } rightRecord = read(rightReader); } rightReader.close(); } for(Record rightRecord : rightRecords) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.RightOuterJoin || joinType == JoinType.FullOuterJoin || joinType == JoinType.InnerJoin ) { write(outputFile, leftRecord, rightRecord); } } } /** * consume all records having key (either to a single list or multiple files) each file will * store a buffer full of data. The right record returned represents the outside flow (key is * already positioned to next one or null) so we can't use this record in below while loop or * within this block in general when comparing current key. The trick is to keep consuming * from a List. When it becomes empty, re-fill it from the next file until all files have * been consumed (and the last node in the list is read). The next outside iteration will be * ready to be processed (either it will be null or it points to the next biggest key * @throws Throwable * */ private Record consume(String key, BufferedReader reader, List<Record> records, List<File> files, long bufferMaxRecordLines ) throws Throwable { boolean processComplete = false; Record record = records.get(records.size() - 1); while(!processComplete){ long recordCount = records.size(); if( record.getKey().compareTo(key) == 0 ){ record = read(reader); while( record != null && record.getKey().compareTo(key) == 0 && recordCount < bufferMaxRecordLines ) { records.add(record); recordCount++; record = read(reader); } } processComplete = true; // if record is null, we are done if( record != null ) { // if the key has changed, we are done if( record.getKey().compareTo(key) == 0 ) { // Same key means we have exhausted the buffer. // Dump entire buffer into a file. The list of file // pointers will keep track of the files ... processComplete = false; dumpBufferToFile(records, files); records.clear(); records.add(record); } } } return record; } /** * Dump all records in List of Record objects to a file. Then, add that * file to List of File objects * * NEED TO PLACE A LIMIT ON NUMBER OF FILE POINTERS (check size of file list) * * @param records * @param files * @throws Throwable */ private void dumpBufferToFile(List<Record> records, List<File> files) throws Throwable { String prefix = "joiner_" + files.size() + 1; String suffix = ".dat"; File file = File.createTempFile(prefix, suffix, new File("cache")); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); for( Record record : records ) { writer.write( record.dump() ); } files.add(file); writer.flush(); writer.close(); }

    Read the article

  • C#/.NET Little Wonders: Constraining Generics with Where Clause

    - by James Michael Hare
    Back when I was primarily a C++ developer, I loved C++ templates.  The power of writing very reusable generic classes brought the art of programming to a brand new level.  Unfortunately, when .NET 1.0 came about, they didn’t have a template equivalent.  With .NET 2.0 however, we finally got generics, which once again let us spread our wings and program more generically in the world of .NET However, C# generics behave in some ways very differently from their C++ template cousins.  There is a handy clause, however, that helps you navigate these waters to make your generics more powerful. The Problem – C# Assumes Lowest Common Denominator In C++, you can create a template and do nearly anything syntactically possible on the template parameter, and C++ will not check if the method/fields/operations invoked are valid until you declare a realization of the type.  Let me illustrate with a C++ example: 1: // compiles fine, C++ makes no assumptions as to T 2: template <typename T> 3: class ReverseComparer 4: { 5: public: 6: int Compare(const T& lhs, const T& rhs) 7: { 8: return rhs.CompareTo(lhs); 9: } 10: }; Notice that we are invoking a method CompareTo() off of template type T.  Because we don’t know at this point what type T is, C++ makes no assumptions and there are no errors. C++ tends to take the path of not checking the template type usage until the method is actually invoked with a specific type, which differs from the behavior of C#: 1: // this will NOT compile! C# assumes lowest common denominator. 2: public class ReverseComparer<T> 3: { 4: public int Compare(T lhs, T rhs) 5: { 6: return lhs.CompareTo(rhs); 7: } 8: } So why does C# give us a compiler error even when we don’t yet know what type T is?  This is because C# took a different path in how they made generics.  Unless you specify otherwise, for the purposes of the code inside the generic method, T is basically treated like an object (notice I didn’t say T is an object). That means that any operations, fields, methods, properties, etc that you attempt to use of type T must be available at the lowest common denominator type: object.  Now, while object has the broadest applicability, it also has the fewest specific.  So how do we allow our generic type placeholder to do things more than just what object can do? Solution: Constraint the Type With Where Clause So how do we get around this in C#?  The answer is to constrain the generic type placeholder with the where clause.  Basically, the where clause allows you to specify additional constraints on what the actual type used to fill the generic type placeholder must support. You might think that narrowing the scope of a generic means a weaker generic.  In reality, though it limits the number of types that can be used with the generic, it also gives the generic more power to deal with those types.  In effect these constraints says that if the type meets the given constraint, you can perform the activities that pertain to that constraint with the generic placeholders. Constraining Generic Type to Interface or Superclass One of the handiest where clause constraints is the ability to specify the type generic type must implement a certain interface or be inherited from a certain base class. For example, you can’t call CompareTo() in our first C# generic without constraints, but if we constrain T to IComparable<T>, we can: 1: public class ReverseComparer<T> 2: where T : IComparable<T> 3: { 4: public int Compare(T lhs, T rhs) 5: { 6: return lhs.CompareTo(rhs); 7: } 8: } Now that we’ve constrained T to an implementation of IComparable<T>, this means that our variables of generic type T may now call any members specified in IComparable<T> as well.  This means that the call to CompareTo() is now legal. If you constrain your type, also, you will get compiler warnings if you attempt to use a type that doesn’t meet the constraint.  This is much better than the syntax error you would get within C++ template code itself when you used a type not supported by a C++ template. Constraining Generic Type to Only Reference Types Sometimes, you want to assign an instance of a generic type to null, but you can’t do this without constraints, because you have no guarantee that the type used to realize the generic is not a value type, where null is meaningless. Well, we can fix this by specifying the class constraint in the where clause.  By declaring that a generic type must be a class, we are saying that it is a reference type, and this allows us to assign null to instances of that type: 1: public static class ObjectExtensions 2: { 3: public static TOut Maybe<TIn, TOut>(this TIn value, Func<TIn, TOut> accessor) 4: where TOut : class 5: where TIn : class 6: { 7: return (value != null) ? accessor(value) : null; 8: } 9: } In the example above, we want to be able to access a property off of a reference, and if that reference is null, pass the null on down the line.  To do this, both the input type and the output type must be reference types (yes, nullable value types could also be considered applicable at a logical level, but there’s not a direct constraint for those). Constraining Generic Type to only Value Types Similarly to constraining a generic type to be a reference type, you can also constrain a generic type to be a value type.  To do this you use the struct constraint which specifies that the generic type must be a value type (primitive, struct, enum, etc). Consider the following method, that will convert anything that is IConvertible (int, double, string, etc) to the value type you specify, or null if the instance is null. 1: public static T? ConvertToNullable<T>(IConvertible value) 2: where T : struct 3: { 4: T? result = null; 5:  6: if (value != null) 7: { 8: result = (T)Convert.ChangeType(value, typeof(T)); 9: } 10:  11: return result; 12: } Because T was constrained to be a value type, we can use T? (System.Nullable<T>) where we could not do this if T was a reference type. Constraining Generic Type to Require Default Constructor You can also constrain a type to require existence of a default constructor.  Because by default C# doesn’t know what constructors a generic type placeholder does or does not have available, it can’t typically allow you to call one.  That said, if you give it the new() constraint, it will mean that the type used to realize the generic type must have a default (no argument) constructor. Let’s assume you have a generic adapter class that, given some mappings, will adapt an item from type TFrom to type TTo.  Because it must create a new instance of type TTo in the process, we need to specify that TTo has a default constructor: 1: // Given a set of Action<TFrom,TTo> mappings will map TFrom to TTo 2: public class Adapter<TFrom, TTo> : IEnumerable<Action<TFrom, TTo>> 3: where TTo : class, new() 4: { 5: // The list of translations from TFrom to TTo 6: public List<Action<TFrom, TTo>> Translations { get; private set; } 7:  8: // Construct with empty translation and reverse translation sets. 9: public Adapter() 10: { 11: // did this instead of auto-properties to allow simple use of initializers 12: Translations = new List<Action<TFrom, TTo>>(); 13: } 14:  15: // Add a translator to the collection, useful for initializer list 16: public void Add(Action<TFrom, TTo> translation) 17: { 18: Translations.Add(translation); 19: } 20:  21: // Add a translator that first checks a predicate to determine if the translation 22: // should be performed, then translates if the predicate returns true 23: public void Add(Predicate<TFrom> conditional, Action<TFrom, TTo> translation) 24: { 25: Translations.Add((from, to) => 26: { 27: if (conditional(from)) 28: { 29: translation(from, to); 30: } 31: }); 32: } 33:  34: // Translates an object forward from TFrom object to TTo object. 35: public TTo Adapt(TFrom sourceObject) 36: { 37: var resultObject = new TTo(); 38:  39: // Process each translation 40: Translations.ForEach(t => t(sourceObject, resultObject)); 41:  42: return resultObject; 43: } 44:  45: // Returns an enumerator that iterates through the collection. 46: public IEnumerator<Action<TFrom, TTo>> GetEnumerator() 47: { 48: return Translations.GetEnumerator(); 49: } 50:  51: // Returns an enumerator that iterates through a collection. 52: IEnumerator IEnumerable.GetEnumerator() 53: { 54: return GetEnumerator(); 55: } 56: } Notice, however, you can’t specify any other constructor, you can only specify that the type has a default (no argument) constructor. Summary The where clause is an excellent tool that gives your .NET generics even more power to perform tasks higher than just the base "object level" behavior.  There are a few things you cannot specify with constraints (currently) though: Cannot specify the generic type must be an enum. Cannot specify the generic type must have a certain property or method without specifying a base class or interface – that is, you can’t say that the generic must have a Start() method. Cannot specify that the generic type allows arithmetic operations. Cannot specify that the generic type requires a specific non-default constructor. In addition, you cannot overload a template definition with different, opposing constraints.  For example you can’t define a Adapter<T> where T : struct and Adapter<T> where T : class.  Hopefully, in the future we will get some of these things to make the where clause even more useful, but until then what we have is extremely valuable in making our generics more user friendly and more powerful!   Technorati Tags: C#,.NET,Little Wonders,BlackRabbitCoder,where,generics

    Read the article

  • IComparable not included when serializing in WCF

    - by djerry
    Hey guys, I have a list i'm filling at server side. It's a list of "User", which implements IComparable. Now when WCF is serializing the data, i guess it's not including the CompareTo method. This is my Object class : [DataContract] public class User : IComparable { private string e164, cn, h323; private int id; private DateTime lastActive; [DataMember] public DateTime LastActive { get { return lastActive; } set { laatstActief = value; } } [DataMember] public int Id { get { return id; } set { id = value; } } [DataMember] public string H323 { get { return h323; } set { h323 = value; } } [DataMember] public string Cn { get { return cn; } set { cn = value; } } [DataMember] public string E164 { get { return e164; } set { e164 = value; } } public User() { } public User(string e164, string cn, string h323, DateTime lastActive) { this.E164 = e164; this.Cn = cn; this.H323 = h323; this.LastActive= lastActive; } [DataMember] public string ToStringExtra { get { if (h323 != "/" && h323 != "") return h323 + " (" + e164 + ")"; return e164; } set { ;} } public override string ToString() { if (Cn.Equals("Trunk Line") || Cn.Equals("")) if (h323.Equals("")) return E164; else return h323; return Cn; } public int CompareTo(object obj) { User user = (User)obj; return user.LastActive.CompareTo(this.LastActive); } } Is it possible to get the CompareTo method to reach the client? Putting [DataMember] isn't the solution as i tried it ( i know...). Thanks in advance.

    Read the article

  • Array.BinarySearch does not find item using IComparable

    - by Sir Psycho
    If a binary search requires an array to be sorted before hand, why does the following code work? string[] strings = new[] { "z", "a", "y", "e", "v", "u" }; int pos = Array.BinarySearch(strings, "Y", StringComparer.OrdinalIgnoreCase); Console.WriteLine(pos); And why does this code result return -1? public class Person : IComparable<Person> { public string Name { get; set; } public int Age { get; set; } public int CompareTo(Person other) { return this.Age.CompareTo(other.Age) + this.Name.CompareTo(other.Name); } } var people = new[] { new Person { Age=5,Name="Tom"}, new Person { Age=1,Name="Tom"}, new Person { Age=2,Name="Tom"}, new Person { Age=1,Name="John"}, new Person { Age=1,Name="Bob"}, }; var s = new Person { Age = 1, Name = "Tom" }; // returns -1 Console.WriteLine( Array.BinarySearch(people, s) );

    Read the article

1 2 3 4 5 6 7 8  | Next Page >