Hey,
So I have an ArrayList that has some people in it.

It's like:

First Name, Last Name, and Position (At a job).

So, I have it make the name complete. so like...

Last name and then first name, no space...

So, then, I need to sort the ArrayList by the complete name...

Any ideas on how to go about this? I've been on it for about 2 hours now, and I can't seem to figure it out... I'd like not to use the Collection.sort as I've tried for a while, and I think it's beyond my abilities... Anyone have any ideas? Even if it's just psuedo or anything, doesn't have to be actual code.

Thanks!

>> I'd like not to use the Collection.sort as I've tried for a while, and I think it's beyond my abilities... Anyone have any ideas? Even if it's just psuedo or anything, doesn't have to be actual code.


if you don't want to use the "sort" function, don't, but you'll still need to write a compareTo function(even if you don't call it that) and you'll need to write a swap function. Or it can all be in one big loop, no functions.

Let's say you have a class called A with two integers in it(b and c) and you want to sort by the value of b. We'll just make everything static and make up a function called GreaterThan (the real way is to write a compareTo function).

// return true if obj1 greater than obj2
public static boolean GreaterThan(A obj1, A obj2)
{
    if(obj1.b > obj2.b) /* since we're sorting on b */
    {
        return true;
    }
    return false;
}

If you're a newbie to Java, don't write a swap function. The whole pass by reference versus pass by value, etc., can be a pain. Just hard code the swap code into wherever you are doing the sort.

Pick a sort, any sort. I like Bubble Sort.

// outer for loop(i)
  // inner for loop(j)
    // call GreaterThan function with objects with indexes i and j
      // swap if necessary based on GreaterThan return value
      // set any flags, if necessary, depending on the sort and the implementation
  // inner loop end
// outer loop end

That's the "write your own" way so you don't have to learn the Comparable interface. But it's more work and you'll want to eventually learn to do it the "right" way.

This article has been dead for over six months. Start a new discussion instead.