Array.sort(Object[], comparator) problems

I have been trying for days to figure out how to sort my array of geneInfo ono the field score1.
when i try to use Arrays.sort(gInfo, new score1Comp()) it turns all of the array null.
class score1Comp implements Comparator
public int compare(Object o1, Object o2)
geneInfo g1 = (geneInfo)o1;
geneInfo g2 = (geneInfo)o2;
// added these checkers to get rid of nullPointerException, but checked to see that most are non null
if(g1==null&&g2==null)
return 0;
if(g1==null)
return -1;
if(g2==null)
return 1;
if(g1.getScore1() == g2.getScore1())
return 0;
else
double temp = g1.getScore1() - g2.getScore1();
System.out.println("score g1 - score g2: " + temp);
System.out.println("rounded: " + (int)Math.round(temp));
return (int)Math.round(temp);
public boolean equals(Object obj)
return obj.equals (this);
}

You have sorting your array with null to be the least on value object. For example here:
MyObject[] objs = new MyObject[1000];
objs[0] = new MyObject(3);
objs[1] = new MyObject(2);
objs[2] = new MyObject(1);
Arrays.sort(objs, new score1Comp());Guess what the result would be? Your array would have the first 997 elements become null and the last 3 would be sorted to (1), (2), (3).
So the cause is how your Comparator treats the null value. The solution could be to make sure your sorting array is filled correctly, or reverse the return 1/-1 for the null treatment.
--lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Need Help with Array.sort and compare

    Hi
    I have a big problem, i try to make a java class, where i can open a file and add new words, and to sort them in a right order
    Ok everthing works fine, but i get a problem with lower and upper cases.
    So i need a comparator, i tried everything but i just dont understand it.
    How do i use this with Array.sort??
    I hope someone can help me

    Okay, you want to ignore case when sorting.
    There are two possibilities: Truly ignore case, so that any of the following are possible, and which one you'll actually get is undefined, and may vary depending on, say, which order the words are entered in the first place:
    English english German german
    english English german German
    English english german German
    english English German german
    The second possibility is that you do consider case, but it's of lower priority--it's only considered if the letters are the same. This allows only the first two orderings above.
    Either way, you need to write a comparator, and call an Arrays.sort method that takes both array and Comparator.
    The first situation is simpler. Just get an all upper or lower case copy of the strings, and then compare thosepublic int compare(Object o1, Object o2) {
        String s1 = ((String)o1).toUpper();
        String s2 = ((String)o1).toUpper();
        return s1.compareTo(s2);
    } You'll need to add your own null check if you need one.
    For the second way, your comparator will need to iterate over each pair of characters. If the characters are equal, ignoring case, then you compare them based on case. You pick whether upper is greater or less than lower.
    Of course, the need to do this assumes that such a method doesn't alrady exist. I don't know of one, but I haven't looked.

  • Array in object overwrite problem

    Hi
    hope you can help me with this as i've already been using too much time solving it myself :)
    I got a Board class which have an ArrayList<ArrayList<Integer>> as attribute. The Board class is controlled from my service class. I need to create a lot of boards which all needs different ArrayList<ArrayList<Integer>> input, so i made a for loop which creates the Boards. The problem is however when i change the variable i used to create the object the values also change inside the object even though the create method have already been called. English isn't my native language so it's a bit hard to explain :) Please ask if there's something you don't understand.
    thanks in advance!
    I made a temporary solution by making a 3d arraylist so i won't have to overwrite any values but thats not rly a good solution as it's starting to give me problems elsewhere.
    the method that creates the boards is Service.importCSV()
    model.Board
    package model;
    import java.util.ArrayList;
    public class Board {
         private String controleNumber;
         private ArrayList<ArrayList<Integer>> numbers = new ArrayList<ArrayList<Integer>>();
         private ArrayList<ArrayList<Integer>> remainingNumbers = new ArrayList<ArrayList<Integer>>();
         public Board(String controlenumber, ArrayList<ArrayList<Integer>> numbers) {
              this.controleNumber = controlenumber;
              this.numbers = numbers;
              this.remainingNumbers = numbers;
         public String getControlenumber() {
              return controleNumber;
         public void setControlenumber(String controleNumber) {
              this.controleNumber = controleNumber;
         public ArrayList<ArrayList<Integer>> getNumbers() {
              return numbers;
         public void setNumbers(ArrayList<ArrayList<Integer>> numbers) {
              this.numbers = numbers;
         public void setRemainingNumbers(ArrayList<ArrayList<Integer>> remainingNumbers) {
              this.remainingNumbers = remainingNumbers;
         public ArrayList<ArrayList<Integer>> getRemainingNumbers() {
              return remainingNumbers;
         public String toString() {
              return String.valueOf(controleNumber);
    }service.Service
    package service;
    import gui.MainFrame;
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import ramdao.BoardDao;
    import model.Board;
    public class Service {
         private static ArrayList<Integer> numbers = new ArrayList<Integer>();
         public static List<Board> getAllBoards() {
              return BoardDao.getAllBoards();
         public static Board createBoard(String controleNumber, ArrayList<ArrayList<Integer>> numbers) {
              Board board = new Board(controleNumber, numbers);
              BoardDao.store(board);
              return board;
         public static void deleteBoard(Board board) {
              BoardDao.remove(board);
         public static Board checkFor(int checkFor) {
              for(Board board : getAllBoards()) {
                   System.out.println(board.getRemainingNumbers());
                   for(ArrayList<Integer> row : board.getRemainingNumbers()) {
                        for(int i=0;i<row.size();i++) {
                             if(numbers.contains(row.get(i))) {
                                  row.remove(row.get(i));
                   if(checkFor==1) {
                        for(ArrayList<Integer> row : board.getRemainingNumbers()) {
                             if(row.size()==0) {
                                  return board;
                   else if(checkFor==2) {
                        if(board.getRemainingNumbers().get(0).size()==0 && board.getRemainingNumbers().get(1).size()==0) {
                             return board;
                        else if(board.getRemainingNumbers().get(0).size()==0 && board.getRemainingNumbers().get(2).size()==0) {
                             return board;
                        else if(board.getRemainingNumbers().get(1).size()==0 && board.getRemainingNumbers().get(2).size()==0) {
                             return board;
                   else if(checkFor==3) {
                        if(board.getRemainingNumbers().size()==0) {
                             return board;
                   System.out.println(board.getRemainingNumbers()  );
              return null;
         public static ArrayList<Integer> oneToGo(int rows, ArrayList<Integer> numbers) {
              //TO-DO
              return null;
         public static void importCSV(ArrayList<String> buff) {
              ArrayList<ArrayList<ArrayList<Integer>>> allNumbers = new ArrayList<ArrayList<ArrayList<Integer>>>();
              int line = 0;
              String controleNumber = "";
              String[] splitLine = new String[10];
              for(int i=0;i<buff.size();i++) {
                   //adds the split buff to splitLine
                   for(int q=0;q<buff.get(i).split(";").length;q++) {
                        if(buff.get(i).split(";")[q].equals(""))
                             splitLine[q]="0";
                        else
                             splitLine[q]=buff.get(i).split(";")[q];
                   if(line==0) {
                        allNumbers.add(new ArrayList<ArrayList<Integer>>());
                        ArrayList<Integer> row = new ArrayList<Integer>();
                        allNumbers.get(allNumbers.size()-1).add(row);
                        controleNumber=buff.get(i).split(";")[0];
                        for(int q=buff.get(i).split(";").length;q<10;q++) {
                             splitLine[q]="0";
                        for(int q=0;q<9;q++) {
                             row.add(Integer.valueOf(splitLine[q+1]));
                   else if(line==1) {
                        ArrayList<Integer> row = new ArrayList<Integer>();
                        allNumbers.get(allNumbers.size()-1).add(row);
                        for(int q=buff.get(i).split(";").length;q<9;q++) {
                             splitLine[q]="0";
                        for(int q=0;q<9;q++) {
                             row.add(Integer.valueOf(splitLine[q]));
                   else if(line==2) {
                        ArrayList<Integer> row = new ArrayList<Integer>();
                        allNumbers.get(allNumbers.size()-1).add(row);
                        for(int q=buff.get(i).split(";").length;q<9;q++) {
                             splitLine[q]="0";
                        for(int q=0;q<9;q++) {
                             row.add(Integer.valueOf(splitLine[q]));
                        createBoard(controleNumber, allNumbers.get(allNumbers.size()-1));
                        line=-1;
                   line++;
         public static ArrayList<String> readFile(File file) {
              FileInputStream fileInputStream = null;
              ArrayList<String> buff = new ArrayList<String>();
              String line;
              try {
                   fileInputStream = new FileInputStream(file);
                   BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
                   while ((line = bufferedReader.readLine())!= null) {
                        buff.add(line);
              catch (IOException ex) {
                   Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
              finally {
                   try {
                        fileInputStream.close();
                   catch (IOException ex) {
                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
              return buff;
         public static void addNumber(int number) {
              numbers.add(number);
         public static ArrayList<Integer> getNumbers() {
              return numbers;
    }

    Tried the code but it's full of compiletime errors. I changed it a little but still got
    Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems:
         board cannot be resolved
         row cannot be resolved
         line cannot be resolved
         board cannot be resolved
         board cannot be resolvedwith the following code
    public static void importCSV(ArrayList<String> buff) {
              ArrayList<ArrayList<ArrayList<Integer>>> allNumbers
              = new ArrayList<ArrayList<ArrayList<Integer>>>();
              String[] splitLine = new String[10];
              String controleNumber;
              for(int i=0;i<buff.size();i++) {
                   int line = i % 3;
                   // split the buffer into fields
                   String[] splitBuf = buff.get(i).split(";");
                   int start = 0;
                   if(line==0) { // new board
                        ArrayList<ArrayList<Integer>> board = new ArrayList<ArrayList<Integer>>();
                        controleNumber = splitBuf[0];
                        start = 1;
                   ArrayList<Integer> row = new ArrayList<Integer>();
                   // fill row from the buffer fields...
                   for(int b = start, last = start+9; b < last; b++) {
                        if(b >= splitBuf.length || splitBuf.length() == 0)
                             row.add(0);
                        else
                             row.add(Integer.valueOf(splitBuf[b]));
              }This is my main problem:createBoard(controleNumber, board);
         board.clear();
         row.clear();The board that i created using the createBord method doesn't hold any numbers because i cleared the arrays i used to create it *after* creating it.
    got my software construction teacher to help me today :)
    works!     public static void importCSV(ArrayList<String> buff) {
              ArrayList<ArrayList<Integer>> board = new ArrayList<ArrayList<Integer>>();
              ArrayList<Integer> row = new ArrayList<Integer>();
              String controleNumber = "";
              int line;
              for(int i=0;i<buff.size();i++) {
                   line = i % 3;
                   String[] splitBuf = buff.get(i).split(";");
                   int start = 0;
                   if(line==0) { // new board
                        board = new ArrayList<ArrayList<Integer>>();
                        controleNumber = splitBuf[0];
                        start = 1;
                   row = new ArrayList<Integer>();
                   // fill row from the buffer fields...
                   for(int b = start, last = start+9; b < last; b++) {
                        if(b >= splitBuf.length || splitBuf[b].length() == 0)
                             row.add(0);
                        else
                             row.add(Integer.valueOf(splitBuf[b]));
                   board.add(row);
                   if(line==2) {
                        createBoard(controleNumber, board);
         }Edited by: Briam on Apr 12, 2010 12:37 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Fastest Array sort method =Flashsort?

    i'm using Array.sort(object) method to sort the array but the running time is getting slower and slower as the size and number of arrays increase.
    As far as i know, Java uses quicksort for Array.sort() and the running time is O(nlogn) with n is the size of the array. Even it's one of the fastest algorithm out there, it will take too long to sort a big number of array.
    I heard that flashsort is the fastest algorithm with running time of O(n). This algorithm is by Dr. Karl-Dietrich Neubert's.
    Anyone wrote one class already that i can use like Flashsort.sort(array a) ?

    There are various implementations of this algorithm on
    this page:
    http://www.neubert.net/Flacodes/FLACodes.html
    I haven't studied it but I had the impression that you
    need to assume some things about the input data to get
    O(n) time complexity; this isn't the only O(n) sorting
    algorithm (radix sort is O(n) too).I think you assume nothing about data. In stead, you need more memory (20%) to sort using FlashSort.
    It is kind of memory for speed sorting. Here is the java code by Roseanne Zhang if you are interested:
    * FlashSort.java
    * Dr. Karl-Dietrich Neubert's Flashsort1 Algorithm
    * http://www.neubert.net/Flapaper/9802n.htm
    * Translation of algorithm into Java by Roseanne Zhang 
    * http://www.webappcabaret.com/javachina
    * Timing measurement included
    * Full functional application
    class FlashSort
        static int   n;
        static int   m;
        static int[] a;
        static int[] l;
         * constructor
         * @param size of the array to be sorted
        public static void flashSort(int size)
            n = size;
            generateRandomArray();
            long start = System.currentTimeMillis();
            partialFlashSort();
            long mid = System.currentTimeMillis();
            insertionSort();
            long end = System.currentTimeMillis();
            // print the time result
            System.out.println("Partial flash sort time     : " + (mid - start) );
            System.out.println("Straight insertion sort time: " + (end - mid) );
         * Entry point
        public static void main(String[] args)
            int size = 0;
            if (args.length == 0)
                usage();
                System.exit(1);
            try
                size = Integer.parseInt(args[0]);
            catch (NumberFormatException nfe) {
                usage();
                System.exit(1);
            FlashSort.flashSort(size);
         * Print usage
        private static void usage()
            System.out.println();
            System.out.println("Usage: java FlashSort n ");
            System.out.println("       n is integer which is the size of array to sort");
         * Generate the random array
        private static void generateRandomArray()
            a = new int[n];
            for (int i=0; i < n; i++)
                a[i] = (int)(Math.random() * 5 * n);
            //printArray(a);
            m = n/20;
            if (m < 30) m = 30;
            l = new int[m];  
         * Partial flash sort
        private static void partialFlashSort()
            int i = 0, j = 0, k = 0;
            int anmin = a[0];
            int nmax  = 0;
            for (i=1; i < n; i++)
                if (a[i] < anmin) anmin=a;
    if (a[i] > a[nmax]) nmax=i;
    if (anmin == a[nmax]) return;
    double c1 = ((double)m - 1)/(a[nmax] - anmin);
    for (i=0; i < n; i++)
    k=(int)(c1*(a[i] - anmin));
    l[k]++;
    //printArray(l);
    for (k=1; k < m; k++)
    l[k] += l[k-1];
    int hold = a[nmax];
    a[nmax]=a[0];
    a[0]=hold;
    int nmove = 0;
    int flash;
    j=0;
    k=m-1;
    while (nmove < n-1)
    while (j > (l[k]-1))
    j++;
    k = (int)(c1 * (a[j] - anmin));
    flash = a[j];
    while (!(j == l[k]))
    k = (int) (c1 * (flash - anmin));
    hold = a[l[k]-1];
    a[l[k]-1]=flash;
    flash = hold;
    l[k]--;
    nmove++;
    //printArray(a);
    * Straight insertion sort
    private static void insertionSort()
    int i, j, hold;
    for (i=a.length-3; i>=0; i--)
    if (a[i+1] < a[i])
    hold = a[i];
    j=i;
    while (a[j+1] < hold)
    a[j] = a[j+1];
    j++;
    a[j] = hold;
    //printArray(a);
    * For checking sorting result and the distribution
    private static void printArray(int[] ary)
    for (int i=0; i < ary.length; i++) {
    if ((i+1)%10 ==0)
    System.out.println(ary[i]);
    else
    System.out.print(ary[i] + " ");
    System.out.println();

  • Sorting an array of objects by an attribute

    I'm pretty new to java so don't laugh if you think my question is real easy!
    I have an array of objects and I want to sort them according to an integer value stored in each object. Any help would be very much appreciated.
    Thanks for looking!!

    Perhaps an example would help:
    public class Person {
      private String name;
      private int age;
      public void setName(String name) { this.name = name; }
      public void setAge(int age) { this.age = age; }
      public String getName() { return name; }
      public int getAge() { return age; }
    =====
    public class PersonAgeSorter implements Comparable {
      public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        Integer i1 = new Integer(p1.getAge());
        Integer i2 = new Integer(p2.getAge());
        return i1.compareTo(i2);
    =====
    public class PersonNameSorter implements Comparable {
      public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        String s1 = p1.getName();
        String s2 = p2.getName();
        return s1.compareTo(s2);
    =====
    import java.util.Arrays;
    public class SortExample {
      public static void main(String [] args) {
      Person p1 = new Person();
      Person p2 = new Person();
      p1.setName("Tom");
      p1.setAge(22);
      p2.setName("Nancy");
      p2.setAge(33);
      Person [] people = new Person[2];
      people[0] = p1;
      people[1] = p2;
      Arrays.sort(people, new PersonAgeSorter());
      Arrays.sort(people, new PersonNameSorter());
    }

  • How to sort an array of objects?

    I need to sort an array of objects. Each object has serial number, and other properties. I need to sort it by serial number.

    Do a java.util.Arrays.sort(). The method has quite a few overloads, so I'll give a complete example this time:import java.util.*
    public class SortDemo {
        public static void main(String args) {
            SimpleObject[] objs = new SimpleObject[10];
            for (int i=0; i<10; i++)
                objs=new SimpleObject();
    dump(objs);
    Comparator c = new SimpleComparator();
    Arrays.sort(objs, c);
    dump(objs);
    static void dump(Object[] o) {
    for (int i=0; i<o.length; i++)
    System.out.print(o[i] + " ");
    /** Object to demonstrate comparing with **/
    class SimpleObject {
    private int n = (int) (10*Math.random());
    public String toString() {
    return String.valueOf(getNumber());
    public int getNumber() {return n;}
    /** The custom comparator **/
    class SimpleComparator implements Comparator {
    public int compare(Object o1, Object o2) {
    return ((SimpleObject) o1).getNumber() - ((SimpleObject) o2).getNumber();
    public boolean equals(Object o) {return false;}
    }I could have made the SimpleObject class "Comparable", but a design like this allows more flexibility so I decided to use another class for the Comparator.

  • I'm having problems Sorting Objects

    Hello everyone!
    I'm having problems sorting objects. Here is what I got at moment... I'm trying using "Collections.sort" with objects, and I think my problem is there but I don't know how to do in other way the sorting.
    Some help will be appreciated! Thank you!
    Movie.java
    import java.util.ArrayList;
    public class Movie
             public int itemNum;
             private String title;
             public String director;
             public Movie()
                 itemNum = -1;
                 title = "";
                 director = "";
             public Movie(int itemNum, String title, String director)
                this.itemNum = itemNum;
                this.title = title;
                this.director = director;
             public int getItemNum()
                 return itemNum;
             public String getTitle()
                 return title;
             public String getDirector()
                 return director;
               public void setItemNum(int a)
                  itemNum = a;
             public void setTitle(String b)
                 title = b;
             public void setDirector(String c)
                 director = c;
             public String toString()
                   String MovieInfo = title + "\t" + itemNum + "\t" + director ;
                   return MovieInfo;
    }MovieCollection.java
    import java.util.*;
    public class MovieCollection
        private ArrayList Movies;
         public MovieCollection()
                Movies = new ArrayList();
         public ArrayList getMovies()
                return Movies;
         public void add(Movie aMovie)
                Movies.add(aMovie);
    }MovieCollectionMenu.java
    import java.io.*;
    import java.util.*;
    public class MovieCollectionMenu
              private MovieCollection model;
              public MovieCollectionMenu ()
                   model = new MovieCollection();
            public MovieCollection getModel()
                return model;
             private static Scanner Insert = new Scanner(System.in);
              public static void main (String[] args)
                  MovieCollectionMenu menu = new MovieCollectionMenu();
                   while(true)
                 System.out.println("Movies Menu");
                 System.out.println("");     
                 System.out.println("1 - Add Movie");
                 System.out.println("2 - List Movies");
                 System.out.println("3 - Sort Movies");
                 System.out.println("0 - Exit");
                    System.out.print("\nSelect your option: ");
                 int option = Insert.nextInt();
                      switch(option)
                           case 0:   System.exit(0);break;
                         case 1:   menu.addMovie(); break;
                         case 2:   menu.listMovies(); break;
                         case 3:   menu.sortMovie(); break;
                         default:  System.out.println("Invalid Selection!");
                      System.out.println("\n");
              private void addMovie()
                   Movie aMovie = new Movie();
                System.out.print("\nEnter movie name: ");
                   aMovie.setTitle(Insert.next());
                 System.out.print("Enter number of copies: ");
                aMovie.setItemNum(Insert.nextInt());
                System.out.print("Enter director name: ");
                aMovie.setDirector(Insert.next());
                model.add(aMovie);
            private void listMovies()
                   ArrayList Movies = model.getMovies();
                   for (int i=0; i<Movies.size(); i++)
                        System.out.println(Movies.get(i).toString());
              private void sortMovie()
                 ArrayList Movies = model.getMovies();
                 Collections.sort(Movies);
    }

    JBStonehenge, Melanie_Green, paulcw thank u so much for ur support!!!!
    I did many changes in my code, and I think in a simple way... I can sort the strings, but I'm having problems to sort the integers from the array I created..
    I read a lot of sorting and this was the best I could do, please can you change my code to sort the integers?
    Thank u people!
    Here it is my code:
    import java.io.*;
    import java.util.*;
    public class MyMovies {
         public static void main(String[] args) {
              MyMovies Movies = new MyMovies();
              Movies.runEverything();
         private static final int MAX_SIZE = 100;
         private static int numberOfMovies = 0;
         private static Movie[] array = new Movie[MAX_SIZE];
         public void runEverything(){
              Scanner input = new Scanner(System.in);
              while (true) {
                   Menu();
                   int option;
                   try {
                        option = Integer.parseInt(input.nextLine());
                   } catch (NumberFormatException e) {
                        System.out.println("You must enter a number!");
                        continue;
    switch (option) {
                   case 1:
                        addMovie(input);
                        System.out.println("\nThis movie was added:");
                        printMovie(numberOfMovies - 1);
                        break;               
                   case 2:
                        sortMoviesByTitle();
                        break;
                   case 3:
                        sortMoviesByYear();
                        break;
                   case 4:
                        sortMoviesByDirector();
                        break;
                   case 5:
                        printAllMovies();
                        break;
                   case 6:
                        System.out.println("You logout with success!");
                        input.close();
                        System.exit(0);
                        break;
              default:
                        System.out.println("You entered a wrong option! Please try again.");
                        break;
         private static void Menu() {
              System.out.println("\n1 - Add a movie");
              System.out.println("2 - Sort movies by name");
              System.out.println("3 - Sort movies by year");
              System.out.println("4 - Sort movies by director");
              System.out.println("5 - Display movies");
              System.out.println("6 - Quit");
              System.out.print("\nPlease enter an option:");
              private static void printMovie(int i) {
              if (i < numberOfMovies) {
                   System.out.println("\"" + array.getTitle() + "\", " + array[i].getYear() + ", \"" + array[i].getDirector() + "\"");
         private void printAllMovies() {
              for (int i = 0; i < numberOfMovies; i++) {
                   System.out.print(String.valueOf(i+1) + "-");
                   printMovie(i);
         private static void addMovie(Scanner input) {
              System.out.print("Enter movie:");
              String title = input.nextLine();
              int year = 0;
              while (true) {
                   try {
                        System.out.print("Enter the year of movie:");
                        year = Integer.parseInt(input.nextLine());
                        break;
                   } catch (NumberFormatException e) {
                        System.out.println("You must enter an integer!");
                        continue;
              System.out.print("Please enter the director:");
              String director = input.nextLine();
              array[numberOfMovies] = new Movie(title, year, director);
              numberOfMovies++;
         private void sortMoviesByTitle(){
         boolean swapped = true;
              int i = 0;
              String tempTitle, tempDirector;
              int tempYear;
              while (swapped) {
                   swapped = false;
                   i++;
                   for (int j = 0; j < numberOfMovies - i; j++) {
                        if ( array[j].getTitle().compareToIgnoreCase(array[j + 1].getTitle()) > 0) {   
                             tempTitle = array[j].getTitle();
                             tempYear = array[j].getYear();
                             tempDirector = array[j].getDirector();
                             array[j].setTitle(array[j + 1].getTitle());
                             array[j].setYear(array[j + 1].getYear());
                             array[j].setDirector(array[j + 1].getDirector());
                             array[j + 1].setTitle(tempTitle);
                             array[j + 1].setYear(tempYear);
                             array[j + 1].setDirector(tempDirector);
                             swapped = true;
              System.out.println("The movies are sorted by title.");
         private void sortMoviesByYear(){
         boolean swapped = true;
              int i = 0;
              String tempTitle, tempDirector;
              int tempYear;
              while (swapped) {
                   swapped = false;
                   i++;
                   for (int j = 0; j < numberOfMovies - i; j++) {
                        if ( array[j].getYear().compareToIgnoreCase(array[j + 1].getYear()) > 0) {   
                             tempTitle = array[j].getTitle();
                             tempYear = array[j].getYear();
                             tempDirector = array[j].getDirector();
                             array[j].setTitle(array[j + 1].getTitle());
                             array[j].setYear(array[j + 1].getYear());
                             array[j].setDirector(array[j + 1].getDirector());
                             array[j + 1].setTitle(tempTitle);
                             array[j + 1].setYear(tempYear);
                             array[j + 1].setDirector(tempDirector);
                             swapped = true;
              System.out.println("The movies are sorted by year.");
         private void sortMoviesByDirector(){
         boolean swapped = true;
              int i = 0;
              String tempTitle, tempDirector;
              int tempYear;
              while (swapped) {
                   swapped = false;
                   i++;
                   for (int j = 0; j < numberOfMovies - i; j++) {
                        if ( array[j].getDirector().compareToIgnoreCase(array[j + 1].getDirector()) > 0) {   
                             tempTitle = array[j].getTitle();
                             tempYear = array[j].getYear();
                             tempDirector = array[j].getDirector();
                             array[j].setTitle(array[j + 1].getTitle());
                             array[j].setYear(array[j + 1].getYear());
                             array[j].setDirector(array[j + 1].getDirector());
                             array[j + 1].setTitle(tempTitle);
                             array[j + 1].setYear(tempYear);
                             array[j + 1].setDirector(tempDirector);
                             swapped = true;
              System.out.println("The movies are sorted by director.");
    /* ----- My Movie Class ----- */
    class Movie {
         private String title;
         private int year;
         private String director;
         public Movie(String title, int year, String director) {
              setTitle(title);
              setYear(year);
              setDirector(director);
         public String getTitle() {
              return title;
         public void setTitle(String title) {
              this.title = title;
         public int getYear() {
              return year;
         public void setYear(int year) {
              this.year = year;
         public String getDirector() {
              return director;
         public void setDirector(String director) {
              this.director = director;
    }Edited by: AntiSignIn on Mar 24, 2010 7:30 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help sorting an array of objects needed please.

    I am trying to sort the array Students[] in descending order of Fees due. Using the code below I get a null pointer error at runtime. The array is not completely full, it has 20 cells, but the variable studentArrayCounter holds the number of used cells. The 'getFeesDue()' code returns an integer value.
    Any help is appreciated.
         // Sort Student Records Method
               public void sortStudentRecords()
                int loopCount = 0;
               for (loopCount = 1; loopCount < studentArrayCounter; loopCount ++)
              if(Students[loopCount].getFeesDue()>Students[loopCount-1].getFeesDue())
                   SortStudents[0]=Students[loopCount-1];
                   Students[loopCount-1]=Students[loopCount];
                   Students[loopCount]=SortStudents[0];
         }

    Also, unless the excersize is to write a sort algorigthm (which I kinda doubt) you should use Arrays.sort
    Arrays.sort(Students, new Comparator() {
      public int compare(Object o1, Object o2) {
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;
        return s1.getFeesDue() - s2.getFeesDue();
    });

  • Sorting an array of objects

    hi there, i have to sort an array of object that looks like:
    surname, name, age, height
    well i have to sort them alphabetically like this:
    based on the surnames, if the surnames are the same than sort on the base of the names; if the names are the same sort them on the base of age and so on. If all the fields are the same the order is non important.
    Well I am not sure how I can do it using the Comparable Interface? as it is an interface i don't have any idea how to implement it

    This search took 2 seconds to do. And it's using your exact subject header. Next time try searching, instead of waiting forever hoping that someone will help you.
    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=&qt=%2B%22sorting+an+array+of+objects%22

  • Java sorting the array of objects

    Hi ,
    I have a question on sorting objects in java.
    I have a java interface some thing like :
    public classmyObj extends Nullable
        private int objId;
        private Datemydate;
        public int getObjID();
        public Date getmyDate();
        public int getISecondD();
      }I need to create the array of the objects of this class that are sorted on the ObjID:
    classmyObj[] collectionObjects
    I need to pass this collectionObjects to another function.
    Now how should I sort these objects based on the ObjID on collection?
    Please help with this!
    Thanks

    neeto wrote:
    Hi ,
    I have a question on sorting objects in java.
    I have a java interface some thing like :You mean class?
    >
    public classmyObj extends Nullable
    private int objId;
    private Datemydate;
    public int getObjID();
    public Date getmyDate();
    public int getISecondD();
    }I need to create the array of the objects of this class that are sorted on the ObjID:
    classmyObj[] collectionObjects
    I need to pass this collectionObjects to another function.
    Now how should I sort these objects based on the ObjID on collection?Create a comparator and use it in a call to Collections.sort (or Arrays.sort if you have an array)

  • How to Sort Array of Object

    Hallo. I have an array of objects. Each object has id and name. How can i sort by name or by id??
    Thx for all
    Max

    array.sortOn("name");

  • Array sort with objects?

    hits = searcher.search(query);
    //java.util.Vector sortHits = new java.util.Vector ();
    int[][] sortHits = new int[hits.length()][1];
    // assign values to array
    int teller = 0;
    for (int i = 0; i < hits.length(); i++)
         Document doc = hits.doc(i);
         String absnumtxt = doc.get("absnumtxt");
         if(sAllCookies.indexOf(absnumtxt) >= 0){
              sortHits[0] = Integer.parseInt(absnumtxt);
              teller++;
              continue;
    But the method Arrays.sort(sortHits); causes a ClassCastException error. Somebody an idea to solve this?
    The structure is:
    sortHits[0][0] = 2
    sortHits[1][0] = 0
    sortHits[2][0] = 0
    sortHits[3][0] = 0
    sortHits[4][0] = 0
    sortHits[5][0] = 0

    A two-dimentional array is an array of array of something.
    Sorting a two-dimentional array requires a Comparator, because you compare uni-dimentional arrays, and arrays are not naturally comparable.
    (BTW, why declaring a two-dimentional array here? you set the second dimention length to 1... a simple array would make it, no?)

  • Sorting an array of Objects based on a variable inside each object

    I have a class public class handInfo
              //VARS
                   int highC = 0;
                   int hVal = 0;
                   int numHand = 0;
              //CONSTRUCOTRS
                   public handInfo()
              //METHODS
                   public void setHC(int hc)
                             highC = hc;
                   public void setHV(int hv)
                             hVal = hv;
                   public void setNH(int nh)
                             numHand = nh;
                   public int getHC()
                             return highC;
                   public int getHV()
                             return hVal;
                   public int getNH()
                             return numHand;
         }now i have an array, handInfo[] hands = new handInfo[4];
                        hands[0] = new handInfo();
                        hands[0].setHC(HV);
                        hands[0].setNH(1);
                        hands[0].setHV(Val);
                        hands[1] = new handInfo();
                        hands[1].setHC(HV2);
                        hands[1].setNH(2);
                        hands[1].setHV(Val2);
                        hands[2] = new handInfo();
                        hands[2].setHC(HV3);
                        hands[2].setNH(3);
                        hands[2].setHV(Val3);
                        hands[3] = new handInfo();
                        hands[3].setHC(HV4);
                        hands[3].setNH(4);
                        hands[3].setHV(Val4);i need to know how to sort this array, based off hVal...
    D:

    Write a Comparator and call Arrays.sort(array, Comparator).

  • Arrays.sort() issue when Numbers are a string!

    Hey guys -- here is my problem.
    I am working on a TOP TEN SCORES mechanism for a trivia game. I have read in the score and the players name from a file. SO I have 2 different arrays topScores[] and topNames[] ---
    Now if someone plays the game and has a higher score than the lowest score, they get to put their score and name in the file and replace the low score.
    HOWEVER -- I do not know how to sort topSCORES[] and then make whatever sorted changes apply also to the topNAMES[] array.
    SO I thought - HEY I will concatenate the topScores and topNames into a single String array. And then SORT! This sounded like a great idea until I realized that the following will happen:
    100 tvance (first one)
    1000 dvance (second score)
    250 danderson (third score) !!!
    See my problem? When I sort this way - it is sorting alphabetically so it will put a 1000 score before a 200-900 score! ---
    **I hope I explained this adequately -- can someone help? Is there a way to sort the topScores array and have it also change the order of the topNames array as well?

    Create a new class - HighScore, which has a highScore and a name?Yup. This technique even has a name: object-oriented programming!
    Demo:
    import java.util.*;
    public final class HighScore implements Comparable<HighScore> {
        private final int score;
        private final String name;
        public HighScore(int score, String name) {
            if (name == null)
                throw new NullPointerException();
            this.score = score;
            this.name = name;
        public int getScore() {
            return score;
        public String getName() {
            return name;
        public int compareTo(HighScore that) {
            if (this.score < that.score)
                return -1;
            else if (this.score > that.score)
                return +1;
            else
                return this.name.compareTo(that.name);
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            else if (obj instanceof HighScore) {
                HighScore that = (HighScore) obj;
                return this.score == that.score && this.name == that.name;
            } else
                return false;
        public int hashCode() {
            return score ^ name.hashCode();
        public String toString() {
            return score + " " + name;
        //demo
        public static void main(String[] args) {
            HighScore[] top = {
                new HighScore(250, "danderson"),
                new HighScore(1000, "dvance"),
                new HighScore(100, "dvance")
            Arrays.sort(top);
            for(int i=0; i<top.length; ++i) {
                System.out.println(top);
    If you are using an older version of Java (1.4 or earlier), the generics won't be
    recognized. In that case the class definition would begin:
    public final class HighScore implements Comparable {And the compareTo method would begin:
    public int compareTo(Object obj) {
        HighScore that = (HighScore) obj;Good luck!

  • Manually Sorting Objects With compareTo

    Hello All,
    I have a quick problem I am working on. I have to implement the java compareTo interface and sort through some objects. I know this would be easier with an array, but all the comparisons of the five objects have to be done through the compareTo. For some reason, the way I am sorting is just not working... I do get output, but there is a bug in my code, and I am assured that the way I am coding is NOT the most efficient. If anyone could guide me, and help me sort the Task objects from highest to lowest based upon Complexity, it would be much appreciated.
    I will try to respond as fast as possible! I have attached the Task class and the class with main below. Thanks again!
    Task Class:
    public class Task implements Comparable
         private String taskName;
         private int priority;
         public Task (String scheduleTaskName, int importance)
              taskName = scheduleTaskName;
              priority = importance;          
         public int compareTo(Object obj)
              Task comparedTask = (Task)obj;
              int comparedTaskPriority = comparedTask.getPriority();
              if (priority < comparedTaskPriority)
                   return -1;
              else if (priority > comparedTaskPriority)
                   return 1;
              else
                   return 0;
         public int getPriority()
              return priority;
         public Task copySelf()
              return this;
         public String toString()
              String result = "P: " + priority + "\t " + taskName;
              return result;
    }Schedule Class:
    //This is the driver class for Task / Comparable implementation.
    public class Schedule
         public static Task task1 = new Task("", 0);
         public static Task task2 = new Task("", 0);
         public static Task task3 = new Task("", 0);
         public static Task task4 = new Task("", 0);
         public static Task task5 = new Task("", 0);
         public static int sortHighest = 0;
         public static void main(String[]args)
              EasyReader console = new EasyReader(System.in);
              //Declare all the variables, but values will be updated as needed.
              //NOTE: These can NEVER be null or there will be errors in the compare!
              System.out.println("Welcome to the complexity scheduler program!");
              System.out.println("We can schedule up to 5 things per day, and rate how complex they are!");
              System.out.println("How many things would you like to schedule today?");
              int numberOfTasks = console.intInput();
              while (numberOfTasks > 5 || numberOfTasks < 1) //Check how valid the input is.
                   System.out.println("We cannot do this many tasks... Please enter a valid number [1-5]:");
                   numberOfTasks = console.intInput();
              System.out.println();
              //Read in all the tasks in an orderly manner.
              for (int x=1; x<=numberOfTasks; x++)
                   System.out.println("Task number " + x + ":");
                   System.out.println("Please enter the task name:");
                   String taskBuffer = console.stringInput();
                   System.out.println("How complex is this task to you?");
                   int importanceBuffer = console.intInput();
                   //Validate the entry that way the sorting will work.
                   while (importanceBuffer <= 0)
                        System.out.println("Please enter a valid importance that is greater than zero! :");
                        importanceBuffer = console.intInput();
                   if(x == 1)
                        task1 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 2)
                        task2 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 3)
                        task3 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 4)
                        task4 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 5)
                        task5 = new Task(taskBuffer, importanceBuffer);
                   System.out.println();
              System.out.println("Thank you for entering in your tasks.");
              System.out.println("Are you ready for them to be sorted and shown? [Y/n]");
              String userChoice = console.stringInput();
              //And here is where we start to sort it.
              if (userChoice.equalsIgnoreCase("y"))
                   System.out.println();
                   sortHighest = numberOfTasks+1;
                   for (int y=1; y <= numberOfTasks; y++)
                        Task temporaryTask;
                        if(y==1)
                             temporaryTask = sortTask(task1);
                        else if (y==2)
                             temporaryTask = sortTask(task2);
                        else if (y==3)
                             temporaryTask = sortTask(task3);
                        else if (y==4)
                             temporaryTask = sortTask(task4);
                        else
                             temporaryTask = sortTask(task5);
                        System.out.println(temporaryTask);
         public static Task sortTask(Task input)
              Task result = input;
              //And the sort goes like this...
              if (result.compareTo(task1) < 0 && task1.getPriority() < sortHighest)
                   result = task1;
              if (result.compareTo(task2) < 0 && task2.getPriority() < sortHighest)
                   result = task2;
              if (result.compareTo(task3) < 0 && task3.getPriority() < sortHighest)
                   result = task3;
              if (result.compareTo(task4) < 0 && task4.getPriority() < sortHighest)
                   result = task4;
              if (result.compareTo(task5) < 0 && task5.getPriority() < sortHighest)
                   result = task5;
              sortHighest = result.getPriority() - 1;
              return result;
    }

    They can be sorted and stored in seperate Task
    objects.. Okay, stop and think about this for a minute.
    The usual way to sort is something like:Arrays.sort(someArray);
    or
    Collections.sort(someList);The sort routine can sort any number of objects--however many are in the list or array.
    Now, your bubblesort method--like the core API's sort methods--will call your compareTo methods on pairs of your objects.
    What will be the signature of your bubblesort method? Will it sort a fixed number of objects?
    bubbleSort(task1, task2, task3, task4, task5)Note that it's impossible for this to even work in Java, because those references will be passed by value. There could not be a separate sort method. You'd have to implement your sort routine inline in the method where they're defined, or they'd have to be member variables. Either way, it's nonsense.
    Not being able to use arrays or lists is a ridiculous requirement. I'm almost certain you misunderstood. Perhaps you're not allowed to use the Arrays.sort method.
    If your teacher really said you can't use arrays, he has no business teaching this class.

Maybe you are looking for