473,323 Members | 1,551 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

what is the wrong with this implementation of Comparable<T>

Hello!

I have the following simple program below.
What is the problem when I get runtime error for
"Failed to compare two elements in the array ?"

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(new Person("tony", 13));
list.Add(new Person("olle", 23));
list.Add(new Person("stina", 53));
list.Add(new Person("august", 3));
list.Add(new Person("roland", 33));

foreach (Person pers in list)
Console.WriteLine(pers.Age);

list.Sort();
foreach (Person pers in list)
Console.WriteLine(pers.Age);
}
}

public class Person : IComparable<Person>
{
string name;
int age;

public Person(string lname, int lage)
{
name = lname;
age = lage;
}

public int Age
{
set {age = value;}
get {return age; }
}

public int CompareTo(Person other)
{
return this.Age - other.Age;
}
}
}
//Tony
Oct 26 '08 #1
5 1294
Tony Johansson wrote:
I have the following simple program below.
What is the problem when I get runtime error for
"Failed to compare two elements in the array ?"

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
You're using ArrayList...
public class Person : IComparable<Person>
But you fail to implement the non-generic interface IComparable.

If you use List<Personinstead of ArrayList (which is a good idea), the
problem disappears, but you should also implement the non-generic
counterpart to IComparable<T>.
public int CompareTo(Person other)
{
return this.Age - other.Age;
}
This implementation is not correct: you must check for the case that "other"
is null (and return a positive value in that case).

--
J.
Oct 26 '08 #2
Hello!

Yes I noticed that my runtime error disapperar when I used List<Tinstad of
ArrayList.
Yes I also know that it's a better solution to use List<Tinstad of
ArrayList.

But I just want to find out what is causing the error when I use the
ArrayList?

//Tony
"Jeroen Mostert" <jm******@xs4all.nlskrev i meddelandet
news:49*********************@news.xs4all.nl...
Tony Johansson wrote:
>I have the following simple program below.
What is the problem when I get runtime error for
"Failed to compare two elements in the array ?"

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();

You're using ArrayList...
> public class Person : IComparable<Person>

But you fail to implement the non-generic interface IComparable.

If you use List<Personinstead of ArrayList (which is a good idea), the
problem disappears, but you should also implement the non-generic
counterpart to IComparable<T>.
> public int CompareTo(Person other)
{
return this.Age - other.Age;
}

This implementation is not correct: you must check for the case that
"other" is null (and return a positive value in that case).

--
J.

Oct 26 '08 #3
On Sun, 26 Oct 2008 10:15:01 -0700, Tony Johansson
<jo*****************@telia.comwrote:
Hello!

Yes I noticed that my runtime error disapperar when I used List<T>
instad of
ArrayList.
Yes I also know that it's a better solution to use List<Tinstad of
ArrayList.

But I just want to find out what is causing the error when I use the
ArrayList?
He told you. You've only implemented IComparable<Person>, not
IComparable. He also pointed out a mistake in your comparison method,
which you should also fix.

For future reference, while it's very good that you included the error
message in your question, you should also be specific about _where_ the
message happens. In this case, it's relatively obvious, but you should
get into the habit of being as specific as possible when asking questions.

Pete
Oct 26 '08 #4
Hello!

Here is the new code implementing IComparable<Tand IComparable.
If I use List<Tit works fine.
If I instead use ArrayList I get runtime error with the message
"Failed to compare two elements in the array ?"
when the List.Sort() is called.

I just want to find the problem tom this runtime error ?

using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(new Person("tony", 13));
list.Add(new Person("olle", 23));
list.Add(new Person("stina", 53));
list.Add(new Person("august", 3));
list.Add(new Person("roland", 33));
list.Sort();
foreach (Person pers in list)
Console.WriteLine(pers.Age);
}
}

public class Person : IComparable<Person>
{
string name;
int age;

public Person(string lname, int lage)
{
name = lname;
age = lage;
}

public int Age
{
set {age = value;}
get {return age; }
}

public int CompareTo(Person other)
{
if (other ==null)
return 1;
return this.Age - other.Age;
}

public int CompareTo(object obj)
{
if (obj is Person)
{
Person pers = obj as Person;
return this.Age - pers.Age;
}
else
{
if (obj == null)
return 1;
throw new ArgumentException("Object to compare to is not a
Person object");
}
}
}
}

"Peter Duniho" <Np*********@nnowslpianmk.comskrev i meddelandet
news:op***************@petes-computer.local...
On Sun, 26 Oct 2008 10:15:01 -0700, Tony Johansson
<jo*****************@telia.comwrote:
>Hello!

Yes I noticed that my runtime error disapperar when I used List<T>
instad of
ArrayList.
Yes I also know that it's a better solution to use List<Tinstad of
ArrayList.

But I just want to find out what is causing the error when I use the
ArrayList?

He told you. You've only implemented IComparable<Person>, not
IComparable. He also pointed out a mistake in your comparison method,
which you should also fix.

For future reference, while it's very good that you included the error
message in your question, you should also be specific about _where_ the
message happens. In this case, it's relatively obvious, but you should
get into the habit of being as specific as possible when asking questions.

Pete

Oct 26 '08 #5
Tony Johansson wrote:
Here is the new code implementing IComparable<Tand IComparable.
It's not actually doing that.
public class Person : IComparable<Person>
This should be

public class Person : IComparable<Person>, IComparable

You must explicitly mention an interface to implement it.

Also, because the non-generic method is strictly less useful than its
generic (strongly typed) counterpart, you should implement it explicitly to
prevent it from being called directly:

int IComparable.CompareTo(object obj) {
if (obj == null) return 1;
if (obj.GetType() != typeof(Person)) throw new ArgumentException();
return this.CompareTo((Person) obj);
}

--
J.
Oct 26 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Eshrath | last post by:
Hi, What I am trying to do: ======================= I need to form a table in html using the xsl but the table that is formed is quite long and cannot be viewed in our application. So we are...
2
by: Donald Firesmith | last post by:
I am having trouble having Google Adsense code stored in XSL converted properly into HTML. The <> unfortunately become &lt; and &gt; and then no longer work. XSL code is: <script...
7
by: Anonymous | last post by:
I have a mixed-language pgm (Fortran and C++) which needs to pass a few hundred values from C++ to Fortran. One way to do this is to have a Fortran module and a C++ structure (or class) with an...
2
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to...
3
by: | last post by:
I have been researching articles on google on how to create a simple RSS feed that sucks <title><blurb><link><date> out of a sql server 2000 database via an aspx page. I know it has to be pushed...
9
by: Simple Simon | last post by:
Java longs are 8 bytes. I have a Java long that is coming in from the network, and that represents milliseconds since Epoch (Jan 1 1970 00:00:00). I'm having trouble understanding how to get it...
11
by: Squeamizh | last post by:
class my_class { public: my_class() : value(0) { } int& get_value() { return value; } const int& get_value() const { my_class& c = const_cast<my_class&>(*this); return c.get_value(); }
1
by: Eran | last post by:
Hi, I have a huge data structure, which I previosly stored in a Dictionary<int, MyObj> MyObj is relatively small (2 int, 1 DateTime, 1 bool). The dictionary I am using is quite large...
3
by: newbie | last post by:
Same thing g++ complains when using hash_map<>, but is happy with map<--I understand hahs_map is not standardized, but since the compiler didn't complain something like 'hash_map<not defined', I...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.