1

I have implemented a comparator class which sorts an array of objects, or "Persons", in my case. However, there seem to be a few bugs, so when I click the next button of my GUI, I get the following error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at RectangleProgram$CustomComparator.compare(RectangleProgram.java:30)
at RectangleProgram$CustomComparator.compare(RectangleProgram.java:26)
at java.util.TimSort.binarySort(TimSort.java:265)
at java.util.TimSort.sort(TimSort.java:208)

Here are snippets of the code that are relevant:

public class Person//HERE IS THE OBJECT THE COMPARATOR IS REFERRING TO
     {
        String firstname; String lastname; int z; 
        public Person(String l, String m, int e)
        {
           firstname=l; lastname=m; z=e; 
        }
        public String getFirstName()
        {
           return firstname;
        }
     } 
public class CustomComparator implements Comparator<Person> { // COMPARATOR BEGINS HERE
      @Override
      public int compare(Person object1, Person object2)
      {
              return object1.getFirstName().compareTo(object2.getFirstName()); 
      }
} // COMPARATOR ENDS HERE
public static Person [] arr=new Person [100]; // ARRAY TO BE SORTED
// class implementing the sort
public class re implements ActionListener
    {
        public void actionPerformed (ActionEvent e) 
        { 
           if (counter==0)
           {
              getData(); 
              Arrays.sort(arr, new CustomComparator()); 
           }

       }
   }

Could someone tell me what is wrong with the code, and is causing the error? Note, it is not a compilation error, it is just that clicking the next button [of which class re is the action listener] does not make it do anything.

1 Answers1

2

I tried this in Java 8

Code:

        List<Person> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Person p = new Person(Integer.toString(i), Integer.toString(i), i);
            list.add(p);
        }
        Collections.shuffle(list);
        System.out.println("the shuffled list");
        list.forEach(i -> System.out.println(i.toString() + " "));
        Collections.sort(list, (p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));
        System.out.println("------------------------ \n the orderd list");
        list.forEach(i -> System.out.println(i.toString() + " "));

output:

the shuffled list
0 0 0 
9 9 9 
8 8 8 
7 7 7 
3 3 3 
6 6 6 
2 2 2 
4 4 4 
1 1 1 
5 5 5 
------------------------ 
 the orderd list
0 0 0 
1 1 1 
2 2 2 
3 3 3 
4 4 4 
5 5 5 
6 6 6 
7 7 7 
8 8 8 
9 9 9 

let me know what happened or you need any explanation

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58