• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 342
  • Last Modified:

Array sort method

I have an Employee class with empid, name and age and there are an array of employee objects created and their fields are initialized. Now how do I  (a)Sort and scramble the array using Arrays.Sort(). Also, how do I ensure the foll:

# anti-commutation : x.compareTo(y) is the opposite sign of y.compareTo(x) .
# exception symmetry : x.compareTo(y) throws exactly the same exceptions as y.compareTo(x) .
# transitivity : if x.compareTo(y)>0 and y.compareTo(z)>0, then x.compareTo(z)>0 (and same for less than) .
# if x.compareTo(y)==0, then x.compareTo(z) has the same sign as y.compareTo(z) .
# consistency with equals is highly recommended, but not required : x.compareTo(y)==0, if and only if x.equals(y) . Any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note:
this class has a natural ordering that is inconsistent with equals."
0
kites
Asked:
kites
  • 4
  • 4
1 Solution
 
a_bCommented:
Is this a homework question? If yes, can you post your attempt?
0
 
kitesAuthor Commented:
Okay, my attempt:
public class EmpSort {
      public static void main(String[] args) {
            Employee[] e = new Employee[3];
            e[0] = new Employee(20111, "James",45);
            e[1] = new Employee(21200, "Reeks",32);
            e[2] = new Employee(20102, "Allen", 30);

            Arrays.sort(e);
      }
}

//EMployee class
public class Employee implements Comparable{

      String name;
      int id;
      int age;
      
      Employee(int id, String name, int age){
            //initialize here
      }
       
       @Override
      public int compareTo(Employee emp) {
            Employee ee= (Employee )emp;
            if(this.id> ee.id) return 1;
            else if(this.id< ee.id) return -1;
            return 0;
      }
0
 
a_bCommented:
Looks like you have everything covered except for the last one -
# consistency with equals is highly recommended, but not required : x.compareTo(y)==0, if and only if x.equals(y) => What is your condition by which 2 employee objects are equal? You may need to override the equals object in your employee class.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
kitesAuthor Commented:
Employees are equal based on age.
Also, how do we scramble the list of employees using Arrays.Sort().
0
 
a_bCommented:
"Employees are equal based on age." -> Are you sure? I think they should be equal based on ids.


"Also, how do we scramble the list of employees using Arrays.Sort()."
Use -
List list = Arrays.asList(array);
Collections.shuffle(list);



0
 
kitesAuthor Commented:
As Arrays.Sort() calls the compareTo() does Collections.shuffle() call it also?
0
 
a_bCommented:
Nope. It does not.
Sorry, I did not read the question correctly.
0
 
for_yanCommented:
You can use another version of
Arrays.sort() method - the one which
also takes object implementing Comparator
as the second parameter.
You can define comparaotr based on comparison of two
randomly generated numbers
then Arrays.sort(array, comparator) method should
effectivelyy scramble the array (see output):


package arraysort;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;


public class ScrambleArray {
    public static void main(String[] args) {
          Employee[] e = new Employee[6];
          e[0] = new Employee(20111, "James",45);
          e[1] = new Employee(21200, "Reeks",32);
          e[2] = new Employee(20102, "Allen", 30);
              e[3] = new Employee(20128, "Peter", 32);
              e[4] = new Employee(20132, "Mark", 25);
              e[5] = new Employee(20001, "Mike", 43);


        Arrays.sort(e, new EmpComp());
                     System.out.println(" ");
                     System.out.println("Scrambled: ");
         System.out.println(" ");

            for(Employee ee: e){
               System.out.println(ee);
           }
        

          Arrays.sort(e);
                  System.out.println(" ");
        System.out.println("Sorted by Id:");
            System.out.println(" ");
        for(Employee ee: e){
            System.out.println(ee);
        }





    }



}

 class Employee implements Comparable<Employee>{

      String name;
      int id;
      int age;

      Employee(int id, String name, int age){
            this.id = id;
          this.name = name;
          this.age = age;
      }

      // @Override
      public int compareTo(Employee emp) {
            Employee ee= emp;
            if(this.id> ee.id) return 1;
            else if(this.id< ee.id) return -1;
            return 0;
      }

     public String toString() {
         String s = id + " " + name + " " + age;
         return s;
     }
 }

class EmpComp implements Comparator<Employee>{
    Random r = new Random();

    public int compare(Employee emp1, Employee emp2){
        int n1 = r.nextInt();
        int n2 = r.nextInt();

  //      System.out.println(n1 + " " + n2);

        if(n1 <n2)return 1;
        else if (n1 > n2)return -1;
        else return 0;



    }

}

Open in new window


Output:
Scrambled: 
 
21200 Reeks 32
20111 James 45
20102 Allen 30
20128 Peter 32
20001 Mike 43
20132 Mark 25
 
Sorted by Id:
 
20001 Mike 43
20102 Allen 30
20111 James 45
20128 Peter 32
20132 Mark 25
21200 Reeks 32

Open in new window

0
 
kitesAuthor Commented:
this is what i was looking for. thanks for_yan!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now