Java Bubble Sort method for Object's fields - java

I want to sort Token objects first based on their usedNumber bigger to smaller.
Then for the tokens have same usedNumber i want to sort them smaller to bigger based their priority number for example:
name priority usedNumber
a 1 3
b 2 4
c 3 0
d 4 3
e 5 3
f 6 4
Sorted version should be first bigger usedNumbers then smaller priorty:
b 2 4
f 6 4
a 1 3
d 4 3
e 5 3
c 3 0
Code below doesnt sort them correctly
public class Token {
int usedNumber;
int priority;
String name;
public Queue<Token> reversebubbleSort(Queue<Token> queue)
{
int n = queue.size();
int i;
int j;
Token temp;
boolean swapped;
for (i = 0; i < n - 1; i++)
{
swapped = false;
for (j = 0; j < n - i - 1; j++)
{
int namenumber1 = Integer.parseInt(queue.get(j).priority);
int namenumber2 = Integer.parseInt(queue.get(j+1).priority);
int number1 = queue.get(j).getUsedNumber();
int number2 = queue.get(j+1).getUsedNumber();
if (((number1^5)-namenumber1) < ((number2^5)-namenumber2))
{
// swap arr[j] and arr[j+1]
temp = queue.get(j);
queue.set(j, queue.get(j+1));
queue.set(j+1, temp);
swapped = true;
}
}
// IF no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
return queue;
}
Queue class in here is not from java.util. This is a class designed by me due the restrictions in my assigment. Queue class uses Arraylists to perform.
public class Queue<Token> {
private ArrayList<Token> queue;
public Queue() {
queue = new ArrayList<>();
}
public void add(Token addItem){
//In queues, adding in the back, first in first out.
queue.add(addItem);
}
public void removeFromFront(){
queue.remove(0);
}
public int size(){
return queue.size();
}
public Token get(int location){
return queue.get(location);
}
public void remove(int index){
queue.remove(index);
}
public void set(int location, Token setItem) {
queue.set(location, setItem);
}
}
}

Rather than wrapping ArrayList in your Queue, extend it: makes for simpler code
Don't use "Token" as a generic class name: it's confusing. Rather use the standard T
Which gives you code for Queue.java:
import java.util.ArrayList;
/*
* If it's only ever used for Token, it could also be
* public class Queue extends ArrayList<Token>
* and then you could override the sort method of ArrayList
* with the implementation shown in Token.sortSpecial below
*/
public class Queue<T> extends ArrayList<T> {
private static final long serialVersionUID = 1L;
public void removeFromFront() {
super.remove(0);
}
}
Method for sorting queues in class Token should be static: it's not linked to the state of an instance. I've renamed it sortSpecial. It also doesn't have to return, as the sorting is done in place on the Queue
Use List.sort with a custom Comparator to do the sorting
Fields should be private with getters and setters (which are not shown here)
Which gives you Token.java:
public class Token {
private String name;
private int priority;
private int usedNumber;
public Token(String name, int priority, int usedNumber) {
super();
this.usedNumber = usedNumber;
this.priority = priority;
this.name = name;
}
/* Getters and Setters go here */
/** Sort by usedNumber DESC / priority ASC */
public static void sortSpecial(Queue<Token> queue) {
queue.sort((x, y) -> {
int comp = -Integer.compare(x.usedNumber, y.usedNumber);
if (comp == 0)
comp = Integer.compare(x.priority, y.priority);
return comp;
});
}
#Override
public String toString() {
return getClass().getSimpleName() + "[" + name + " (p=" + priority + ", un=" + usedNumber + ")]";
}
}
Or if you want to play smart-ass, you could write the comparator as a one-liner (after defining your getters):
Comparator.comparingInt(Token::getUsedNumber).reversed().thenComparingInt(Token::getPriority)
Entry point for your program (Main.java):
public class Main {
public static void main(String[] args) {
Queue<Token> toks = new Queue<>();
toks.add(new Token("a", 1, 3));
toks.add(new Token("b", 2, 4));
toks.add(new Token("c", 3, 0));
toks.add(new Token("d", 4, 3));
toks.add(new Token("e", 5, 3));
toks.add(new Token("f", 6, 4));
System.out.println("Input:");
toks.stream().forEach(t -> System.out.println('\t' + t.toString()));
System.out.println();
Token.sortSpecial(toks);
System.out.println("Output:");
toks.stream().forEach(t -> System.out.println('\t' + t.toString()));
}
}
Console output:
Input:
Token[a (p=1, un=3)]
Token[b (p=2, un=4)]
Token[c (p=3, un=0)]
Token[d (p=4, un=3)]
Token[e (p=5, un=3)]
Token[f (p=6, un=4)]
Output:
Token[b (p=2, un=4)]
Token[f (p=6, un=4)]
Token[a (p=1, un=3)]
Token[d (p=4, un=3)]
Token[e (p=5, un=3)]
Token[c (p=3, un=0)]

Related

Why am I getting null on a line that compares two indices in my priority queue heap?

I am making a priority queue heap of type T. When I add more than one integer to my heap, I get a null pointer exception on line 55, which is where the reheapUp method uses the comparator to decide which integer gets priority.
I've been stuck on this for hours. At first I thought I had to implement a generic compare method but that doesn't make sense because there would be nothing specific enough to compare. The compare method I am using is from an old project where I made a binary search tree map that compared strings.
/*
* PQHeap.java
* 11/12/18
*/
import java.util.Comparator;
import java.util.*;
public class PQHeap<T>{
private Object[] heap; //hash table
private int heapSize;
private int capacity;
private Comparator<T> comparator;
public PQHeap(Comparator<T> comparator){
heapSize = 0;
capacity = 100;
heap = new Object[capacity];
}
public int size(){
return this.heapSize;
}
public void add(T obj){
ensureCapacity();
//add to lower right most leaf
heap[heapSize++] = obj;
reheapUp();
}
public void ensureCapacity(){
if(heapSize < heap.length/2)
return;
Object newHeap[] = new Object[2*heap.length];
for(int i=0; i<heap.length; i++)
newHeap[i] = heap[i];
heap = newHeap;
}
#SuppressWarnings("unchecked")
private void reheapUp(){
int outOfPlaceInd = heapSize - 1;
while(outOfPlaceInd > 0){
int parentInd = (outOfPlaceInd - 1)/2;
**if (comparator.compare((T)heap[outOfPlaceInd], (T)heap[parentInd]) < 0)**
{
swap(outOfPlaceInd, parentInd);
outOfPlaceInd = (outOfPlaceInd-1)/2;
}
else{
return;
}
}
}
private void swap(int i, int j){
Object copy = heap[i];
heap[i] = heap[j];
heap[j] = copy;
}
#SuppressWarnings("unchecked")
public T remove(){
if(heapSize == 0)
throw new IllegalStateException("Trying to remove from an empty PQ!");
Object p = heap[0];
heap[0] = heap[--heapSize];
reheapDown();
return (T)p;
}
#SuppressWarnings("unchecked")
private void reheapDown(){
int outOfPlaceInd = 0;
int leftInd = 2*outOfPlaceInd+1; //left child
int rightInd = 2*outOfPlaceInd+2; //right child
while(leftInd <= heapSize-1){
int smallerChildInd = leftInd;
if ((rightInd < heapSize) && (comparator.compare((T)heap[rightInd], (T)heap[leftInd]) < 0))
smallerChildInd = rightInd;
// is the parent smaller or equal to the smaller child
int compare = comparator.compare((T)heap[outOfPlaceInd], (T)heap[smallerChildInd]);
// if the parent is larger than the child...swap with smaller child
if (compare > 0)
{
swap(outOfPlaceInd, smallerChildInd);
// update indices
outOfPlaceInd = smallerChildInd;
leftInd = 2*outOfPlaceInd + 1;
rightInd = 2*outOfPlaceInd + 2;
}
else
{
return;
}
}
}
public static void main( String[] args ) {
PQHeap<Integer> pq = new PQHeap<Integer>(new TestIntComparator());
pq.add( 10 );
pq.add( 20 );
System.out.println(pq.size());
pq.add( 20 );
pq.add( 30 );
class TestIntComparator implements Comparator<Integer> {
public TestIntComparator() {;}
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
}
}
}
// class NaturalComparator<T extends Comparable<T>> implements Comparator<T> {
// public int compar(T a, T b) {
// return a.compareTo(b);
// }
// }
In PQHeap constructor you don't assign input comparator object to class field. Add line like this:
this.comparator = comparator;
in your constructor

Sequence of random numbers without repeats

I am trying to do a pvp event in my game server which uses 3 zones to do it randomly. I use the following code but always is returning me the values 1 and 2 and repeated as well. I need some sequence like this for example: 3-2-1-2-1-3 or something that never repeats the same number.
int random = Rnd.get(1, 3);
if (random == 1)
{
setstartedpvpzone1(true);
}
if (random == 2)
{
setstartedpvpzone2(true);
}
if (random == 3)
{
setstartedpvpzone3(true);
}
this is what i get in rnd:
public final class Rnd
{
/**
* This class extends {#link java.util.Random} but do not compare and store atomically.<br>
* Instead it`s using a simple volatile flag to ensure reading and storing the whole 64bit seed chunk.<br>
* This implementation is much faster on parallel access, but may generate the same seed for 2 threads.
* #author Forsaiken
* #see java.util.Random
*/
public static final class NonAtomicRandom extends Random
{
private static final long serialVersionUID = 1L;
private volatile long _seed;
public NonAtomicRandom()
{
this(++SEED_UNIQUIFIER + System.nanoTime());
}
public NonAtomicRandom(final long seed)
{
setSeed(seed);
}
#Override
public final int next(final int bits)
{
return (int) ((_seed = ((_seed * MULTIPLIER) + ADDEND) & MASK) >>> (48 - bits));
}
#Override
public final void setSeed(final long seed)
{
_seed = (seed ^ MULTIPLIER) & MASK;
}
}
and rnd.get:
/**
* Gets a random integer number from min(inclusive) to max(inclusive)
* #param min The minimum value
* #param max The maximum value
* #return A random integer number from min to max
*/
public static final int get(final int min, final int max)
{
return rnd.get(min, max);
}
If all you are looking for is a random number that doesn't equal the previous one returned then the solution is much simpler:
private Random random = new Random();
private int previousZone = 0;
public int nextZone() {
int zone;
do {
zone = random.nextInt(3) + 1;
} while (zone == previousZone);
previousZone = zone; //store last "generated" zone
return zone;
}
[not tested] It is possible that it may contain some syntax errors as I am not a Java programmer.
int a=0,b=0;
while(true)
{
int random = Rnd.get(1, 3);
if(!(a==random or b==random))
{
a=b;
b=random;
break;
}
}
if (random == 1)
{
setstartedpvpzone1(true);
}
if (random == 2)
{
setstartedpvpzone2(true);
}
if (random == 3)
{
setstartedpvpzone3(true);
}
Your problem boils down to a graph traversal in which from each current zone, you only have 2 possible next zones and those choices never change. So here is how I would implement it:
public static class EventLocator{
private int currentZone;
private Random random;
private Map<Integer, int[]> locations;
private static EventLocator instance;
private EventLocator() {
}
public static EventLocator getInstance(){
if (instance == null) {
instance = new EventLocator();
}
return instance;
}
public int getNextZone(){
if (this.currentZone == 0) {//first time called
this.random = new Random();
this.locations = new HashMap<>(3);//graph <currentZone, posibleZones>
this.locations.put(1, new int[] { 2, 3 });
this.locations.put(2, new int[] { 1, 3 });
this.locations.put(3, new int[] { 1, 2 });
this.currentZone = this.random.nextInt(3) + 1;// to 1-based Zones
return currentZone;
}
int[] possibleZones = this.locations.get(this.currentZone);
int randomIndex = this.random.nextInt(2);//0 or 1 index
this.currentZone = possibleZones[randomIndex];
return this.currentZone;
}
}
You would call it like:
EventLocator eventLocator = MyProgram.EventLocator.getInstance();
System.out.println(eventLocator.getNextZone());
System.out.println(eventLocator.getNextZone());
This code never repeats any numbers, for example if you have 1,2,3 you can get a random sequence of 4 numbers, example 2,1,3.
Create an array with all numbers you need...
int[] a = {1, 2, 3};
Then select random items
for (int i=0; i<a.length; i++){
int random = Rnd.get(0, a.length);
//remove the selected item from the array
ArrayUtils.removeElement(a, random);
if (random == 1) {
setstartedpvpzone1(true);
} else if (random == 2) {
setstartedpvpzone2(true);
} else if (random == 3) {
setstartedpvpzone3(true);
}
}
private boolean _lastevent1 = false;
public boolean lastevent1()
{
return _lastevent1;
}
public void setlastevent1(boolean val)
{
_lastevent1 = val;
}
private boolean _lastevent2 = false;
public boolean lastevent2()
{
return _lastevent2;
}
public void setlastevent2(boolean val)
{
_lastevent2 = val;
}
private boolean _lastevent3 = false;
public boolean lastevent3()
{
return _lastevent3;
}
public void setlastevent3(boolean val)
{
_lastevent3 = val;
}
if (!lastevent1())
{
setlastevent3(false);
setstartedpvpzone3(false);
setstartedpvpzone1(true);
setlastevent1(true);
}
else if (!lastevent2())
{
setstartedpvpzone1(false);
setstartedpvpzone2(true);
setlastevent2(true);
}
else if (!lastevent3())
{
setlastevent1(false);
setlastevent2(false);
setstartedpvpzone2(false);
setstartedpvpzone3(true);
setlastevent3(true);
}
hello finally i fixed using booleans and i get this secuence, 1-2-3-1-2-3-1-2-3-1-2-3 , i breaked my mind with it because is very confuse this code but it work now as a charm , thanks for all to try to help me i very appreciate it, great community.

What is the most efficient way to simultaneously sort three ArrayLists in Java

I have three ArrayLists. One of Strings - names, and two of Integers - score and picture numbers. I want to sort them simultaneously by the players scores (from highest to lowest). Now i use a simple bubble sort, but i think it will not be efficient when the Lists will be bigger.
This is my code:
public class MyBubbleSort {
public static void bubble_srt(List<Integer> score, List<String> name, List<Integer> pic) {
int n = score.size();
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (score.get(i) < score.get(k)) {
swapNumbers(i, k, score, name, pic);
}
}
printNumbers(score);
}
}
private static void swapNumbers(int i, int j, List<Integer> score, List<String> name, List<Integer> pic) {
int temp;
temp = score.get(i);
score.set(i, score.get(j));
score.set(j, temp);
String s;
s = name.get(i);
name.set(i, name.get(j));
name.set(j, s);
int p;
p = pic.get(i);
pic.set(i, pic.get(j));
pic.set(j, p);
}
private static void printNumbers(List<Integer> input) {
for (int i = 0; i < input.size(); i++) {
System.out.print(input.get(i) + ", ");
}
System.out.print("\n");
}
}
Thanks!
Best way would be to create a class containing score, name and pic properties and have a single List of that class, which you sort using Collections.sort and a Comparator that compares two instances of your class according to the score property.
Bubble sort is in-efficient compared to other sorting algorithms (merge sort, quick sort), and there's no need to implement a sort algorithm yourself, since the standard Java packages already do that for you.
First create a PlayerInfo class as follows:
package test;
public class PlayerInfo {
private String name;
private Integer score;
private Integer pictureId;
public PlayerInfo(final String name, final Integer score, final Integer pictureId) {
this.name = name;
this.score = score;
this.pictureId = pictureId;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public Integer getScore() {
return this.score;
}
public void setScore(final Integer score) {
this.score = score;
}
public Integer getPictureId() {
return this.pictureId;
}
public void setPictureId(final Integer pictureId) {
this.pictureId = pictureId;
}
#Override
public String toString() {
return this.name + ":" + this.score + ":" + this.pictureId;
}
}
Second create a PlayerInfo Comparator. Here we create a ScoreBasedComparator (as per your request, but you can create other comparators as well to fit your specific needs):
package test;
import java.util.Comparator;
public class ScoreBasedComparator implements Comparator<PlayerInfo> {
#Override
public int compare(final PlayerInfo playerInfo1, final PlayerInfo playerInfo2) {
return playerInfo1.getScore().compareTo(playerInfo2.getScore());
}
}
Finally, you can sort your List of PlayerInfo instances, using Collections.sort(<your collection>, <your comparator>) as follows:
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Runner {
public static void main(final String[] args) {
List<PlayerInfo> playerInfos = new ArrayList<PlayerInfo>();
playerInfos.add(new PlayerInfo("A", 123, 1));
playerInfos.add(new PlayerInfo("B", 1, 2));
playerInfos.add(new PlayerInfo("C", 23, 3));
playerInfos.add(new PlayerInfo("D", 300, 4));
Collections.sort(playerInfos, new ScoreBasedComparator());
System.out.println(Arrays.toString(playerInfos.toArray()));
}
}
Running this small program will output the following line:
[B:1:2, C:23:3, A:123:1, D:300:4]
As you can see your collection was unsorted at creation time but is printed sorted by score.
Hope this helps.
If the goal here is to sort three arrays according to one of the arrays, without resorting to combining the arrays into a common class, then a fourth array of indices, 0 to size-1 can be created, then the array of indices is sorted according to one of the arrays (using a built in sort and custom compare). Then all three arrays are reordered according to the array of sorted indices. I don't know if Java has a built in reorder function. C example to reorder 3 arrays, A,B,C according to sorted array of indices I, with time complexity of O(n) (linear, every store places a value in it's ordered position). I is reverted back to 0 to n-1.
// reorder A,B,C in place according to I
// tA,tB,tC are temps
for(i = 0; i < n; i++){
if(i != I[i]){
tA = A[i];
tB = B[i];
tC = C[i];
k = i;
while(i != (j = I[k])){
A[k] = A[j];
B[k] = B[j];
C[k] = C[j];
I[k] = k;
k = j;
}
A[k] = tA;
B[k] = tB;
C[k] = tC;
I[k] = k;
}
}

ArrayList<Item> (where Item is inner class) adding wrong

I have a class called Bag2 and it has inner class called Item. Bag2 has variable ArrayList aList and function called "add". It's adding wrong by repeat adding duplicate value.
Here is my code:
import java.util.ArrayList;
public class Bag2 {
public Bag2(){}; // Constructor
/**
* Inner class
*
*/
public class Item implements Comparable<Item> {
String name;
int quantity;
public Item(String name, int quantity) { // Constructor
this.name = name;
this.quantity = quantity;
}
#Override
public String toString() {
return name + " : " + quantity;
}
#Override
public int compareTo(Item o) {
return name.compareToIgnoreCase(o.name);
}
}
public ArrayList<Item> aList = new ArrayList<>();
public void add(String itemName){
Bag2 bag2 = new Bag2();
Bag2.Item item = bag2.new Item(itemName.toUpperCase(), 1);
if (aList.isEmpty()){
aList.add(item);
} else
{
for(int i = 0; i < aList.size();i++){
if (item.compareTo(aList.get(i))==0){
aList.get(i).quantity++;
}else {
aList.add(item); // Built inn add-function
break; // add one time only and the size increases
}
}
}
}
}
And here is my test :
public class Bag2Test {
public static void main(String[] args) {
Bag2 bag = new Bag2();
Bag2.Item[] anArray =
{
bag.new Item("A", 1),
bag.new Item("B", 1),
bag.new Item("C", 1),
bag.new Item("D", 1),
bag.new Item("a", 1),
bag.new Item("F", 1),
bag.new Item("b", 1),
bag.new Item("e", 1),
bag.new Item("a", 1)
};
for (int i = 0; i<anArray.length; i++ ){
bag.add(anArray[i].name); //
}
System.out.println("\nA list contains : ");
for (int i = 0; i<bag.aList.size(); i++) {
System.out.println(bag.aList.get(i));
}
}
}
and output:
A list contains :
A : 3
B : 1
C : 1
D : 1
A : 1
F : 1
B : 1
E : 1
A : 1
Your add function is broken because it can trigger the statement if (item.compareTo(aList.get(i))==0) for one i value and still add it for another value. While there are more elegant and robust solutions for you program including overriding equals()and hashCode() and using a Set instead of a list, that would result in a generic bag implementation and I posted the shortest fix for your problem.
public void add(String itemName)
{
Bag2 bag2 = new Bag2();
Bag2.Item item = bag2.new Item(itemName.toUpperCase(), 1);
if (aList.isEmpty())
{
aList.add(item);
} else
{
boolean existing = false;
for(int i = 0; i < aList.size();i++)
{
if (item.compareTo(aList.get(i))==0)
{
aList.get(i).quantity++;
existing=true;
break;
}
}
if(!existing) {aList.add(item);}
}
}
Let's say you add the following items : A,B,C
now your list is : A:1, B:1, C:1
In your add logic you check if the current item is the same one, otherwise you add the item. So if we now try to add item C again your list will look like this: A:1, B:1, C:1, C:1
This is because you are checking item by item. Before adding the new item you need to check that it does not exist in the ENTIRE list and only then add it. (e.g. When adding C to the above list the first loop iteration (i=0) will execute the code in the else block since C and A are different and C will be added although it does exist in the list)

InventoryItem.java uses unchecked or unsafe operations

I'm learning about comparable and am implementing it in my Inventory class. However when I go to compile the code, the compiler gives an error.
InventoryItem.java uses unchecked or unsafe operations.
Can anyone please help me out. What is wrong with my code and what can I do to fix this issue. Thank you for your help in advance.
class InventoryItem implements Comparable<InventoryItem>
{
private String name;
private int uniqueItemID;
public InventoryItem()
{
name = " ";
uniqueItemID = 0;
}
public InventoryItem(String newName, int newItemID)
{
name = newName;
uniqueItemID = newItemID;
}
public InventoryItem(InventoryItem i)
{
name = i.name;
uniqueItemID = i.uniqueItemID;
}
public void setName(String newName)
{
name = newName;
}
public void setItemID(int newItemID)
{
uniqueItemID = newItemID;
}
public int getItemID()
{
return uniqueItemID;
}
public String getName()
{
return name;
}
public int compareTo(InventoryItem i)
{
int anotherUniqueID = i.getItemID();
return (this.uniqueItemID - anotherUniqueID);
}
public static void sort(Comparable[] a, int numberUsed)
{
int index, indexOfNextSmallest;
for(index = 0; index < numberUsed - 1; index++)
{
indexOfNextSmallest = indexOfSmallest(index, a, numberUsed);
interchange(index, indexOfNextSmallest, a);
}
}
private static int indexOfSmallest(int startIndex, Comparable[] a, int numberUsed)
{
Comparable min = a[startIndex];
int indexOfMin = startIndex;
int index;
for(index = startIndex + 1; index < numberUsed; index++)
{
if(a[index].compareTo(min) < 0)
{
min = a[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int i, int j, Comparable[] a)
{
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public class InventoryItemTester
{
public static void main(String [] args)
{
InventoryItem[] items = new InventoryItem[3];
items[0] = new InventoryItem("Pens", 2);
items[1] = new InventoryItem("Pencils", 3);
items[2] = new InventoryItem("Notebooks", 1);
System.out.println("Before sorting");
System.out.println(items[0]);
System.out.println(items[1]);
System.out.println(items[2]);
InventoryItem.sort(items, items.length);
System.out.println("After sorting");
System.out.println(items[0]);
System.out.println(items[1]);
System.out.println(items[2]);
}
}
At a guess I'd say this line is causing the issue (Your compiler tells you exactly which line is the problem, this might be useful to include in your next question):
private static int indexOfSmallest(int startIndex, Comparable[] a, int numberUsed)
{
Comparable min = a[startIndex];
int indexOfMin = startIndex;
int index;
for(index = startIndex + 1; index < numberUsed; index++)
{
here==========> if(a[index].compareTo(min) < 0)
{
You are calling compareTo with a InventoryItem where it is expecting an Object. You could add a #SuppressWarnings annotation which would make it go away :)
The basic idea of Comparable and Comparator is they apply a sorting order to an Object so that the standard JDK Collections objects can do all the hard work for you.
In your case your comparesTo method does the correct thing, however I'm not sure if this is good planning or good luck, so things to note:
InventoryItem.comparesTo method needs to evaluate the current instance to the provided instance and return an integer signifying the ordering, -1 means the instance (ie this) should be ordered before the argument, 0 means they are the same and 1 means the instance is after the argument. Something like this lets the JDK do all the hard work for you
public int compareTo(InventoryItem i)
{
return Integer.valueOf(this.uniqueItemID).compareTo(i.uniqueItemID);
}
In order to use Comparable all you really need to do is implement it and then use the standard JDK Collections classes to do all the heavy lifting for you, eg:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class InventoryItemTest
{
public static void main(String [] args)
{
List<InventoryItem> items = new ArrayList<InventoryItem>();
items.add(new InventoryItem("Pens", 2));
items.add(new InventoryItem("Pencils", 3));
items.add(new InventoryItem("Notebooks", 1));
System.out.println("Before sorting");
System.out.println(items);
Collections.sort(items);
System.out.println("After sorting");
System.out.println(items);
}
}
I realise this might not be as much fun as writing your own sorting algorithms but if you want to do that with no compiler warnings then you need to start looking at generics

Categories