Sorting dilemma

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • blackraven1425
    New Member
    • Mar 2008
    • 27

    #1

    Sorting dilemma

    I need to sort objects (called items) in an ArrayList by a given field (name, price, etc). What is the easiest way to do this? I'm not sure how to write a comparator, if Collections.sor t is the easiest method. Then that becomes my question: how do I write a comparator that changes which field to compare depending on a value?
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    Define a method called compareTo in your items class, and compare them that way. Then declare that your items class implements the Comparable interface, and Collections.sor t should work just fine.

    Comment

    • blackraven1425
      New Member
      • Mar 2008
      • 27

      #3
      But my problem is, how do I change which value to check against? There's only one argument for compareTo, and I think I'd need another to show which value to check against. How would I do this part of the problem.

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        You could have a static variable in your class indicating which value to compare between, assuming every instance of item will be compared by the same value at any time.

        Comment

        • blackraven1425
          New Member
          • Mar 2008
          • 27

          #5
          thanks, i didnt think of that haha. that helps alot!

          Comment

          Working...