Results 1 to 5 of 5

Thread: Comparing Objects

  1. #1

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Resolved Comparing Objects

    If i have two objects how can i compare them?

    For example.

    I have two objects of the same class. They have a variable called 'data' which is a string.

    Object 1: data = 'hello'
    Object 2: data = 'bye'

    I want to compare these objects to see which object would come first (alphabetically) if the 'data' variable of both objects was sorted into alphabetical order.

    The order i would be order is Obect 2 and then Object 1, but how can i do this in code?

    Thanks.
    Last edited by x-ice; Feb 24th, 2007 at 07:12 PM.

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Comparing Objects

    You can implement the interface "Comparable" in your class and return the String.compareTo(String) value
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  3. #3

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: Comparing Objects

    Quote Originally Posted by ComputerJy
    You can implement the interface "Comparable" in your class and return the String.compareTo(String) value
    Can you give an example on how to do this? I am pretty rusty at Java these days.

  4. #4
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Comparing Objects

    Code:
    public class Sample implements Comparable
    {
      private String str ;
    
      public String getString () {
        return str ;
      }
    
      public int compareTo (Object o) {
        if (o instanceof Sample) {
          return str.compareTo(((Sample) o).getString()) ;
        }
        else {
          return str.compareTo(o.toString()) ;
        }
      }
    }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  5. #5

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: Comparing Objects

    Quote Originally Posted by ComputerJy
    Code:
    public class Sample implements Comparable
    {
      private String str ;
    
      public String getString () {
        return str ;
      }
    
      public int compareTo (Object o) {
        if (o instanceof Sample) {
          return str.compareTo(((Sample) o).getString()) ;
        }
        else {
          return str.compareTo(o.toString()) ;
        }
      }
    }
    Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width