简体   繁体   中英

Bubble sort Arraylist of objects

The aim of this method here is to bubble sort according to a person's ID

however in this area:

if (al.get(i).compareTo(al.get(i+1)) > 0 )

it states: cannot find symbol - method compareTo(java.lang.Object)


This is the class person (not very imp) / / / /

public class Person implements java.io.Serializable
{
  String personID;
  String name;
  byte dayDOB;
  byte monthDOB;
  short yearDOB;
  String telNum;
}

This is the sort method:

public static void sort(ArrayList al)
  {
   Person p;
   String temp;
   boolean flag = true;

   System.out.println("Database will be sorted acc to ID ");
   System.out.println();


    while (flag = true)
    {
        flag = false;

        for (int i=0;i<al.size()-1;i++)    
        {
            p = (Person) al.get(i);

            if (al.get(i).compareTo(al.get(i+1)) > 0 )
            {
                temp = al.get(i);
                al.set(i,al.get(i+1) );
                al.set(i+1, temp);
                flag = true;
            }
        }
    }
    }

PS; I am a newbie when it comes to code and have been modifying this code for up to 7 hours already

Objects come with a built in compareTo() method, but it's best to override the default. See the java documentation for compareTo() . That should simplify your code quite a bit.

Your Person class will need to implement Comparable and include that in the class declaration. You can then write a compareTo() method something like this:

public int compareTo(Person b) {
   return this.name.compareTo(b.getName());
}

A compareTo() method should return -1, 0, or 1. If you call a.compareTo(b) in your main class, compareTo() should return zero if the objects are sorted to the same place (ie equal), -1 if object a should be sorted before object b, or 1 if object a should be sorted after b.

You'll need to decide what constitutes the same person and how they should be sorted. Alphabetically based on name? Name and id? Whatever it is for your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM