however, to do this, you must modify your classes. each item in the list (each of his java objects) must implement the Comparable interface, and have a public method named compareTo(). so, to sort his list the way he wanted to, he had to write
Code: Select all
public class Lump implements Comparable<Lump>
{
public int index;
public int compareTo(Lump otherLump)
{
// do comparison based on what we know about Lumps
int ourIndex = this.index;
int theirIndex = otherLump.index;
if (ourIndex < theirIndex)
return -1;
else if (ourIndex > theirIndex)
return 1;
else
return 0;
}
}
python:
Code: Select all
# class
class Lump(object):
def __init__(self, index=0):
self.index = index
# sort function
def sortLump(a, b):
if a.index < b.index:
return -1
elif a.index > b.index:
return 1
else:
return 0
# create three lumps, place them in a list and sort them
l1 = Lump(10)
l2 = Lump(5)
l3 = Lump(20)
ls = [ l1, l2, l3 ]
ls.sort(sortLump)
Code: Select all
# create the class
Object subclass: #Lump
instanceVariableNames: 'index'
classVariableNames: ''.
# "getter and setter" methods for the index instance variable
Lump >> index
"return value of index instance variable."
^ index!
Lump >> index: aNumber
"set index's value."
index := aNumber
# ----------------------------------------------
# and now, the code to create a list with three elements, and sort it
| l1 l2 l3 arr |
l1 := Lump new index: 10.
l2 := Lump new index: 5.
l3 := Lump new index 20.
arr := Array with: l1 with: l2 with: l3.
arr sort: [ :a :b | (a index) < (b index) ].
ruby steals a lot of ideas from smalltalk, so its code looks similar:
Code: Select all
class Lump
attr_accessor :index
def initialize(index)
@index = index
end
end
l1 = Lump.new(10)
l2 = Lump.new(5)
l3 = Lump.new(20)
arr = Array.new(l1, l2, l3)
arr.sort { |x, y| x.index <=> y.index }