HyObject.java - Data Element Class

This section describes a sample data element class, HyObject.java, which can be used to represent the data objects that you want to put them in a collection and sort them.

Here is my sample data element class, HyObject.java, that implements Comparable<HyObject> interface defined in JDK:

/* HyObject.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.util.*;
public class HyObject implements Comparable<HyObject> {
   private Object data;
   private int keyValue;
   private static Random randomGenerator;
   public static void setRandom(int s) {
      randomGenerator = new Random(s);
   }
   public HyObject() {
      data = null;
      keyValue = randomGenerator.nextInt(999999);
   }
   public int compareTo(HyObject d) {
      if (this.keyValue>d.keyValue) {
         return 1;
      } else if (this.keyValue<d.keyValue) {
         return -1;
      } else {
         return 0;
      }
   }
   public String toString() {
      return String.valueOf(keyValue);
   }
}

Note that:

If you are still using older versions of Java that support only the raw "Comparable" interface type, here is my old sample data element class, HyObjectOld.java:

/*  HyObjectOld.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.util.*;
public class HyObjectOld implements Comparable {
   private Object data;
   private int keyValue;
   private static Random randomGenerator;
   public static void setRandom(int s) {
      randomGenerator = new Random(s);
   }
   public HyObjectOld() {
      data = null;
      keyValue = randomGenerator.nextInt();
   }
   public int compareTo(Object d) {
      if (this.keyValue>((HyObjectOld)d).keyValue) {
         return 1;
      } else if (this.keyValue<((HyObjectOld)d).keyValue) {
         return -1;
      } else {
         return 0;
      }
   }
   public String toString() {
      return String.valueOf(keyValue);
   }
}
public void setKeyValue(int keyValue) {
  this.keyValue = keyValue;
}
public int getKeyValue(int keyValue) {
  return keyValue;
}

Table of Contents

 About This Book

 Introduction of Sorting Algorithms

Java API for Sorting Algorithms

 Why Java API Is Needed

HyObject.java - Data Element Class

 SortTest.java - Testing Program

 java.util.Arrays.sort() - Performance

 Performance Summary of Java Implementations

 Insertion Sort Algorithm and Java Implementation

 Selection Sort Algorithm and Java Implementation

 Bubble Sort Algorithm and Java Implementation

 Quicksort Algorithm and Java Implementation

 Merge Sort Algorithm and Java Implementation

 Heap Sort Algorithm and Java Implementation

 Shell Sort Algorithm and Java Implementation

 Sorting Algorithms Implementations in PHP

 Sorting Algorithms Implementations in Perl

 Sorting Algorithms Implementations in Python

 Performance Summary of All Implementations

 References

 Full Version in PDF/EPUB