Click to See Complete Forum and Search --> : generic sorting


cashmoney
March 9th, 2009, 11:26 AM
Hi,
I would like to sort objects then to put them in increasing order.
I wrote into a standard code that I tries to adapt to objects but not evident, especially that it does not accept the operator ">".
Ps : I would like to sort everything i want. String, Integer and else...


public class Utilitaires {

public static Object triGen (Object[] trigen){
int i;
Object retenue;
boolean tri;
do {
tri = false;
for (i = 1; i < trigen.length; i++) {
if (trigen[i] > trigen[i + 1]) {
retenue = trigen[i];
trigen[i] = trigen[i + 1];
trigen[i + 1] = retenue;
tri = true;
}
}

} while (tri);
}

}



In eclipse, it puts this error trigen [ i ] > trigen [i + 1]): the operator ">" is undefined for the argument type . And when I try " compareTo ", he asks me to create a corresponding method, but I do not know which arguments or syntax to put in the compareTo.
Thanks

ProgramThis
March 9th, 2009, 12:21 PM
That is because the Object class is a generic object class that EVERY single Java class is derived from. When you try to say that Object a is > Object b Java has no idea what > means for these unknown object types.

The compareTo method should be defined for every class that you want to be Comparable. String and Integer are already Comparable (i.e. they have implemented the compareTo method for these classes). So if you pass in Integer or String objects you should be able to call the a.compareTo(b) method.

However, you cannot pass in unknown Objects and expect this to work. You either need to directly cast these objects into their types OR you need to learn Java Generics.

Check out This Link (http://books.google.com/books?id=fI6dl1flmk8C&pg=PA348&lpg=PA348&dq=java+%22generic+compareto+method%22&source=bl&ots=kyxNOrMYjO&sig=-S4pJ47t9FlpW21lcaES47IP9h4&hl=en&ei=VlW1SeLqKc-jtgfDi_3pDA&sa=X&oi=book_result&resnum=1&ct=result#PPA348,M1) to see how.

cashmoney
March 10th, 2009, 04:21 AM
Thanks,
so if I want to use compareTo, I must override it but I do not have idea of syntax which I must write. If you can help me, it would be great.
I start to write a compareto method but, I need lighted coder to correct if it is right.

public static Object max (Object o1, Object o2)
{
if (o1.compareTo(o2) > 0)
return o1;
else return o2;
}


This code do not work because my the compareTo is underlined in red.
Thanks

ps : sorry for my english

cashmoney
March 10th, 2009, 08:49 AM
Hi,
I try another code, but I do not try it yet 'cause my main code is not finish.

public class Utilitaires {

// Tri générique d'objects contenus dans un tableau
public static <T> Object triGen(T[] trigen) {
boolean trie = false;
while(!trie){
trie = true;
for(int j=0;j<trigen.length;j++){
if(((Comparable) trigen[j]).compareTo(trigen[j+1]) > 0 ){
swapper(trigen, j, j+1);
trie = false;
}
}
}return trigen;
}

public static <T> void swapper(T[] tab, int i, int j){
// TODO Auto-generated method stub
T temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}
}

ProgramThis
March 10th, 2009, 08:50 AM
Your compareTo is underlined in red because there is no compareTo method defined in the Object class. You are passing in raw Objects so without casting them to their types Java doesn't know what to do.

Maybe dlorde or somebody else can help you to create a generic method for comparing generic types. Please READ THIS article (http://books.google.com/books?id=fI6dl1flmk8C&pg=PA348&lpg=PA348&dq=java+%22generic+compareto+method%22&source=bl&ots=kyxNOrMYjO&sig=-S4pJ47t9FlpW21lcaES47IP9h4&hl=en&ei=VlW1SeLqKc-jtgfDi_3pDA&sa=X&oi=book_result&resnum=1&ct=result) about how to create a generic compare method. That method can then take any type that is comparable (Which String and Number are) and allow you to compare them without knowing the type before hand.

I am not that good with Generics so I will defer to the really brilliant on here to help you with that code, but get started and "try" to follow the link I gave you and try to write your own generic compare method.

cashmoney
March 10th, 2009, 10:10 AM
Ok, I go to read your article.

cashmoney
March 10th, 2009, 10:14 AM
Hey, I am reading your article and it is from your article I wrote my code. So I continue

dlorde
March 10th, 2009, 03:42 PM
Maybe dlorde or somebody else can help you to create a generic method for comparing generic types.There's not a lot to say really - the Comparable class and compareTo(..) method are already generic. The standard Java technique is to implement the Comparable interface, and then the objects can be treated as Comparables and the compareTo(..) method can be called on them, e.g:class Foo implements Comparable<Foo> {
...
int compareTo(Foo o) {
...
}
}If a class doesn't implement Comparable, you can compare instances using a Comparator, but you'd have to write it, and using it wouldn't be generic - you'd have to use the right Comparator for the class in question, and I can't offhand think of a way to make it generic (although you could map the comparators to the class types in a map collection).

If we wish to count lines of code, we should not regard them as lines produced but as lines spent...
E. Dijkstra

cashmoney
March 11th, 2009, 08:32 AM
Thanks for your helps, I try it.

cashmoney
March 11th, 2009, 08:47 AM
I tried your exemple, but it underlined my compareTo ( The method compreTo(Object) is undefined for the type Object)


public class Utilitaires implements Comparable {

public int compareTo(Object o1) {
Object o2 = null;
if (o1.equals(o2))
return 0;
else if (o1.!equals(o2))
return -1;
else
return 1;
}
// Tri générique d'objects contenus dans un tableau
public static <T> Object triGen(T[] trigen) {
boolean trie = false;
while (!trie) {
trie = true;
for (int j = 0; j < trigen.length; j++) {
Object a;
Object b;
a = trigen[j];
b = trigen[j + 1];
if (a.compareTo(b) > 0) {
swapper(trigen, j, j + 1);
trie = false;
}
}
}
return trigen;
}
public static <T> void swapper(T[] tab, int i, int j) {
// TODO Auto-generated method stub
T temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}
}

ProgramThis
March 11th, 2009, 09:06 AM
That is because, as stated earlier, the compareTo method IS undefined for the Object class. Try comparing trigen[j].compareTo(trigen[j + 1]) and let me know if that works.

cashmoney
March 11th, 2009, 09:40 AM
ok, I am wainting for you.

so, I wrote this code, but I have this error


Exception in thread "main" java.lang.ClassCastException: Coloriage.Coloriage cannot be cast to Coloriage.Utilitaires
at Coloriage.Utilitaires.triGen(Utilitaires.java:38)
at Coloriage.Principal.main(Principal.java:62)



public class Utilitaires implements Comparable {

public int compareTo (Object obj) {
Object o1 = ((Utilitaires) obj);
Object o2 = this;

if (((Utilitaires) o1).compareTo(o2) < 0) {
return -1;
}
else if (((Utilitaires) o1).compareTo(o2) == 0) {
return 0;
}
else {
return 1;
}
}


// Tri générique d'objects contenus dans un tableau
public static <T> Object triGen(T[] trigen) {
boolean trie = false;
while (!trie) {
trie = true;
for (int j = 0; j < trigen.length; j++) {
Object a;
Object b;
a = trigen[j];
if (((Utilitaires) a).compareTo(b)> 0) ------------>Utilitaires.java:38 error
{
swapper(trigen, j, j + 1);
trie = false;
}
}
}
return trigen;
}

public static <T> void swapper(T[] tab, int i, int j) {
// TODO Auto-generated method stub
T temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}

}

dlorde
March 11th, 2009, 10:15 AM
Comparable is generic, so Utilitaires should be:public class Utilitaires implements Comparable<Utilitiaires> {

public int compareTo (Utilitiaires ut) {
return ...
}
}The code you had inside the compareTo method was calling the Utilitiaire compareTo method - which is a recursive call and will result in a stack overflow. There has to be some data in Utilitiaires to compare, otherwise there's nothing to sort on. That data is what you should compare in your compareTo method.

I just can't make sense of your 'trigen' method at all - it takes an array of generic type T and returns it as an Object, it casts each member to a Utilitiaire and tries to compare it with an uninitialised (null) object 'b'...

The nearest I can get to what I think you may be trying to do with the generics is this:public static <T extends Comparable<T>> T[] triGen(T[] trigen) {
boolean trie = false;
while (!trie) {
trie = true;
for (int j = 0; j < trigen.length; j++) {
T a = trigen[j];
T b = trigen[j+1];
if (a.compareTo(b) > 0) {
swapper(trigen, j, j + 1);
trie = false;
}
}
}
return trigen;
}This takes an array of things that extend Comparable, compares the elements, does some swaps, and returns the array. The whole thing will break if it ever reads the last array element because trying to access j+1 will fall off the end of the array, and I'm not sure what that 'trie' boolean will do, but I'll leave that for you to work out.

The point of using generics in this way to replace the specific types with a generic type, so you don't use Object or any other specific type.

You might find the Generics FAQ (http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) informative.

It is better to have an approximate answer to the right question than an exact answer to the wrong one...
J. Tukey

cashmoney
March 11th, 2009, 10:32 AM
In fact, my class utilitaires have a triGen(), function that i use to sort all objects i want. my prolem is not to sort but to compare to object.
this is my program squeleton

public class Principal {

static void main(String[] args) {
// TODO Auto-generated method stub
Couleur rouge = Couleur.ROUGE;
Coloriage c1 = new Coloriage(rouge);
...
Coloriage tabCoulTrie2[] = (Coloriage[]) Utilitaires.triGen(tabCoul);
...

public enum Couleur {

ROUGE("ROUGE"), VERT("VERT"), BLEU("BLEU"), ORANGE("ORANGE"), JAUNE("JAUNE"), VIOLET("VIOLET");
private String libelle;
private Couleur (String inLabel){
this.libelle = inLabel;
...
public class Coloriage {

private Couleur c;
public Coloriage(Couleur inC) {
this.c = inC;
}
...

public class Utilitaires implements Comparable {


public int compareTo (Object) {
....How to Compare 2 Objects and validate it in my triGen() function or method.


public static <T> Object triGen(T[] trigen) {
...

cashmoney
March 11th, 2009, 10:56 AM
...main
Coloriage tabCoulTrie2[] = (Coloriage[]) Utilitaires.triGen(tabCoul);
....

triGen------>Bound mismatch : the generic method triGen(T[]) of type Utilitaires is not applicable for the arguments (Coloriage[]). The inferred type Coloriage is not a valid suvstitute for the bounded parameter <T extends Comparable<T>>


this is my class Utilitaires

public class Utilitaires {

//Tri générique d'objects contenus dans un tableau
public static <T extends Comparable<T>> Object triGen(T[] trigen) {
boolean inverse; // vrai si on effectue au moins une inversion de

do {
inverse = false;
for (int i = 0; i < trigen.length - 1; i++)
{
T a = trigen[i];
T b = trigen[i+1];
if (a.compareTo(b) > 0)
{
inverse = true; // le tableau n'est pas encore ordonné
swapper(trigen, i, i+1);
}
}
} while (inverse); // trier tant qu'il reste des éléments non
// ordonnés, donnant lieu à des inversionsreturn trigen;
return trigen;
}

public static <T> void swapper(T[] tab, int i, int j) {
// TODO Auto-generated method stub
T temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}
}

dlorde
March 11th, 2009, 03:23 PM
In fact, my class utilitaires have a triGen(), function that i use to sort all objects i want. my prolem is not to sort but to compare to object.
We seem to be talking at cross-purposes...

The reason for a class to implement the Comparable interface is to compare instances of that class with each other using the compareTo method. Before generics were introduced into the language, the parameter of the compareTo method had to be an Object because the interface declaration would be implemented in many different classes. Each class had to check that the Object passed to it was the correct type, then cast it to the correct type. With generics, it is possible to specify the exact type that will be implementing the interface every time, so type checking and casting is not required (see the Utilitaires code I posted earlier).

If you want to do something different that involves comparing Objects, I don't understand how you can do that. The Utilitiaires class only knows about its own type, what can it do with an Object that isn't a Utilitiaire?

It seems to me that you can either implement Comparable the old way, where you pass an Object, check its type, and cast it to Utilitiaire for the comparison, or do it the new way with generics and avoid all that. I don't think you can achieve anything by trying to use both.

If you want to implement Comparable in Utilitiaires, I've given you the code. If not, I don't know what you're trying to achieve.

If we spoke a different language, we would perceive a somewhat different world...
L. Wittgenstein

dlorde
March 11th, 2009, 03:50 PM
As I already said, the trigen method I posted takes an array of objects that implement Comparable. This means the method knows that they all have a properly implemented compareTo method. If you try to pass in an array of objects that don't implement Comparable properly (see the Utilitiaire code I posted), it will give you an error. So your Coloriage class must implement the Comparable interface if you want to use it in the trigen method.

You can change the code I gave you as much as you like, but unless you understand what you're doing, the chances are it won't work. To me, it appears that you don't have a clear understanding of how interfaces are used and not enough understanding of generics to use them successfully.

You don't need generics to make this sorting method, you can remove the generics completely and just make sure all the classes you want to sort implement the Comparable interface. But whichever way you do it, they must all implement Comparable if you want to be able to use the trigen method to sort them.

For example, without generics (you don't need Object anywhere in this):public static Comparable[] triGen(Comparable[] trigen) {
boolean trie = false;
while (!trie) {
trie = true;
for (int j = 0; j < trigen.length; j++) {
Comparable a = trigen[j];
Comparable b = trigen[j+1];
if (a.compareTo(b) > 0) {
swapper(trigen, j, j + 1);
trie = false;
}
}
}
return trigen;
}The only advantage generics gives you over this is that you can keep the exact array type all through, instead of having to cast the return value from Comparable[] back to an array of the type you started with, e.g:Foo[] fooArray = ...; // get array of Foo (which implements Comparable)

// without generics
fooArray = (Foo[]) triGen(fooArray); // cast required

// with generics
fooArray = triGen(fooArray); // no cast requiredIf you don't understand what I'm saying, you probably need to learn more about interfaces and generics. If you think I have misunderstood what you are trying to do, please explain as clearly as you can.

p.s. Please use the CODE tags rather than the PHP tags when posting Java code.

Increasingly, people seem to misinterpret complexity as sophistication, which is baffling -the incomprehensible should cause suspicion rather than admiration. Possibly this trend results from a mistaken belief that using a somewhat mysterious device confers an aura of power on the user...
N. Wirth

cashmoney
March 12th, 2009, 05:28 AM
Ok, so I go to try to learn more and finish my program.

cashmoney
March 12th, 2009, 08:47 AM
I followed your advices, I bent seriously over all the information which you have give to me and I took out this code.

public class Utilitaires<E extends Comparable<? super E>> {

// Tri générique d'objects contenus dans un tableau
public static <E extends Comparable<? super E>> E[] triGen(E[] trigen) {
boolean trie = false;
while (!trie) {
trie = true;
for (int j = 0; j < trigen.length - 1; j++) {

if (trigen[j].compareTo(trigen[j + 1]) < 0) {
swapper(trigen, j, j + 1);
trie = false;
}
}
}
return trigen;
}
public static <E extends Comparable<? super E>> E maximum(E a, E b) {
return a.compareTo(b) > 0 ? a : b;
}

public static <T> void swapper(T[] tab, int i, int j) {
// TODO Auto-generated method stub
T temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}
}


Then I implemented comparable on my class coloriage


public class Coloriage implements Comparable<Coloriage> {

private Couleur c;
...


And It works.
Thanks for all advices, God bless y'all.

dlorde
March 12th, 2009, 10:00 AM
Great! Thanks for letting us know the solution :thumb:

We shall do a much better programming job, provided we approach the task with a full appreciation of its tremendous difficulty, provided that we respect the intrinsic limitations of the human mind and approach the task as very humble programmers...
A. Turing

cashmoney
March 12th, 2009, 10:21 AM
I give you all my program code, It consists to create colors(class couleur) and mixed them by Colouring ( class coloriage) and sort created color using class enum.
MAIN

public class Principal {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Couleur rouge = Couleur.ROUGE;
Couleur bleu = Couleur.BLEU;

Coloriage c1 = new Coloriage(bleu);
Coloriage c2 = new Coloriage(rouge);
Coloriage c3 = new Coloriage(Couleur.ORANGE);
Coloriage c4 = new Coloriage(Couleur.VERT);

c1 = new Coloriage(c2);
c1 = new Coloriage("bleu");

if (c1.equals(c1))
Afficher.obj("\n c1 == c1 ");
if (c1.equals(c2))
Afficher.obj("\n c1 == c2 ");
c1.setCouleur("BLEU");
c1.setCouleur(Couleur.BLEU);
Coloriage c10 = c1.melanger(c2);

Afficher.obj((c10));
Afficher.obj(c10.toString());
Afficher.obj(c10);
Coloriage tabCoul[] = new Coloriage[4];
tabCoul[0] = c1;
tabCoul[1] = c2;
tabCoul[2] = c3;
tabCoul[3] = c4;
if (c1.compareTo(c2) == 0 )
Afficher.obj("==");
Afficher.obj("\n tabCoul = ");
for (int i = 0; i < tabCoul.length; i++) {
Afficher.obj("\n " + tabCoul[i]);
}
Coloriage tabCoulTrie[] = trier(tabCoul);
Afficher.obj("\n tabCoulTrie = ");
for (int i = 0; i < tabCoulTrie.length; i++) {
Afficher.obj("\n " + tabCoulTrie[i]);
}
tabCoul[0].setCouleur(Couleur.VERT);
tabCoul[1].setCouleur(Couleur.ROUGE);
tabCoul[2].setCouleur(Couleur.BLEU);
tabCoul[3].setCouleur(Couleur.ORANGE);
Coloriage tabCoulTrie2[] = (Coloriage[]) Utilitaires.triGen(tabCoul);
Afficher.obj("\n tabCoulTrie 2 = ");
for (int i=0;i<tabCoulTrie2.length;i++){
Afficher.obj("\n : "+tabCoulTrie2[i]);
}
}
private static Coloriage[] trier(Coloriage[] tabCoul) {
// TODO Auto-generated method stub
boolean trie = false;
while(!trie){
trie = true;
for(int j=0;j<tabCoul.length-1;j++){
if(tabCoul[j].getCouleur().ordinal() > tabCoul[j+1].getCouleur().ordinal() ){
permuter(tabCoul, j, j+1);
trie = false;
}
}
}
return tabCoul;
}

private static void permuter(Coloriage[] tab, int i, int j) {
// TODO Auto-generated method stub
Coloriage temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}
}


class Couleur(color)

public enum Couleur {

ROUGE("ROUGE"), VERT("VERT"), BLEU("BLEU"), ORANGE("ORANGE"), JAUNE("JAUNE"), VIOLET("VIOLET");
private String libelle;
private Couleur (String inLabel){
this.libelle = inLabel;
}
public String getLibelle(){
return libelle;
}
public void setLibelle( String inLabel){
this.libelle = inLabel;
}
}


class coloriage(colouring)

public class Coloriage implements Comparable<Coloriage> {

private Couleur c;

public Coloriage() {
// TODO Auto-generated constructor stub
c = Couleur.ROUGE;
}

/**
* @param c
*/
public Coloriage(Couleur inC) {

this.c = inC;
}

// constructeur de recopie
public Coloriage(Coloriage inCol) {
// TODO Auto-generated constructor stub

this.c = inCol.c;

}

public Coloriage(String str) {
// TODO Auto-generated constructor stub
this.setCouleur(str);

}

public Couleur getCouleur() {
// TODO Auto-generated method stub
return c;
}

public void setCouleur(Couleur inC) {
// TODO Auto-generated method stub
this.c = inC;
}

public void setCouleur(String str) {
if (str.toUpperCase().equals(("ROUGE")))
this.c = Couleur.ROUGE;
else if (str.toUpperCase().equals(("VERT")))
this.c = Couleur.VERT;
else if (str.toUpperCase().equals(("BLEU")))
this.c = Couleur.BLEU;
else if (str.toUpperCase().equals(("ORANGE")))
this.c = Couleur.ORANGE;
else if (str.toUpperCase().equals(("JAUNE")))
this.c = Couleur.JAUNE;
else if (str.toUpperCase().equals(("VIOLET")))
this.c = Couleur.VIOLET;
}

public Coloriage melanger(Coloriage cl) {
// TODO Auto-generated method stub
if ((this.c == Couleur.ROUGE) && (cl.getCouleur() == Couleur.BLEU)
|| (this.c == Couleur.BLEU)
&& (cl.getCouleur() == Couleur.ROUGE))
cl = new Coloriage(Couleur.VIOLET);
else if ((this.c == Couleur.ROUGE) && (cl.getCouleur() == Couleur.VERT)
|| (this.c == Couleur.VERT)
&& (cl.getCouleur() == Couleur.ROUGE))
cl = new Coloriage(Couleur.JAUNE);
else if ((this.c == Couleur.ROUGE)
&& (cl.getCouleur() == Couleur.JAUNE)
|| (this.c == Couleur.JAUNE)
&& (cl.getCouleur() == Couleur.ROUGE))
cl = new Coloriage(Couleur.ORANGE);
return cl;

// return null;
}

public int compareTo(Coloriage cl) {
//this.c = cl.getCouleur();
if (this.c.ordinal() > cl.getCouleur().ordinal())
return 1;
else if (this.c.ordinal() < c.ordinal())
return -1;
else
return 0;
}

public String toString() {
return c.getLibelle();
}
}


Class utilitaires


public class Utilitaires<E extends Comparable<? super E>> {

// Tri générique d'objects contenus dans un tableau
public static <E extends Comparable<? super E>> E[] triGen(E[] trigen) {
boolean trie = false;
while (!trie) {
trie = true;
for (int j = 0; j < trigen.length - 1; j++) {

if (trigen[j].compareTo(trigen[j + 1]) > 0) {
swapper(trigen, j, j + 1);
trie = false;
}
}
}
return trigen;
}
public static <E extends Comparable<? super E>> E maximum(E a, E b) {
return a.compareTo(b) > 0 ? a : b;
}

public static <T> void swapper(T[] tab, int i, int j) {
// TODO Auto-generated method stub
T temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}
}

dlorde
March 12th, 2009, 03:20 PM
OK - it certainly gives some interesting results...

Remember that now you're using generics for Utilitiaires.trigen, you don't have to cast the return value back to (Coloriage[]) - that's the reason for using generics... and it will work just as well with <E extends Comparable<E>>

The person who says it cannot be done should not interrupt the person doing it...
Chinese Proverb

cashmoney
March 13th, 2009, 03:21 AM
OK, I won't forget it

ProgramThis
March 13th, 2009, 09:28 AM
I was bored and wanted to try working with Generics thanks to your problem, so I added some stuff to your code, just for... fun?

NOW, I know I know... Collections.sort(list); .... I just couldn't help myself but to reinvent the wheel.

Next time dlorde, suggest he use ArrayLists instead of arrays!!!! lol :lol:


public class GenericSortUtility {
// Tri générique d'objects contenus dans un tableau
public static <E extends Comparable<? super E>> E[] genericSorter(E[] array) {
boolean trie = false;
while (!trie) {
trie = true;
for (int j = 0; j < array.length - 1; j++) {

if (array[j].compareTo(array[j + 1]) > 0) {
swapper(array, j, j + 1);
trie = false;
}
}
}
return array;
}

/**
* This method is able to sort any class that is Comparable and meets the Java 1.5
* standards for such.
*
* @param <E>
* @param list
* @return
*/
public static <E extends Comparable<? super E>> List<E> genericListSorter(List<E> list) {
boolean done = false;
while(!done) {
done = true;
for(int i = 0 ; i < list.size() - 1 ; i++) {
if(list.get(i).compareTo(list.get(i + 1)) > 0) {
swapperList(list,i,i + 1);
done = false;
}
}
}
return list;
}

/**
* Swaps two elements in a Generic arary at indexes i and j.
*
* @param <T>
* @param tab
* @param i
* @param j
*/
public static <T> void swapper(T[] tab, int i, int j) {
// TODO Auto-generated method stub
T temp = tab[i];
tab[i] = tab[j];
tab[j] = temp;
}

/**
* This method will swap the elements in the list at indexes i and j.
*
* @param <T>
* @param list
* @param i
* @param j
*/
public static <T> void swapperList(List<T> list, int i , int j) {
T temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}

/**
* This method is never called that I can see, but I left it in there in case
* you are calling it from some other class.
*
* @param <E>
* @param a
* @param b
* @return
*/
public static <E extends Comparable<? super E>> E maximum(E a, E b) {
return a.compareTo(b) > 0 ? a : b;
}

public static void main(String args[]) {
String array[] = {"Hello","Boy","Girl","Tommy","Alphabet","Henry","Naomi","Frank"};
List<Integer> intList = new ArrayList<Integer>();
for(int i = 0; i < 100; i++) {
intList.add(new Integer((int)(Math.random()*100)));
}

List<String> list = new ArrayList<String>();
List<String> colSorted = new ArrayList<String>();
List<String> sortedList = new ArrayList<String>();
for(int i = 0 ; i < array.length ; i++){
list.add(array[i]);
colSorted.add(array[i]);
sortedList.add(array[i]);
}

System.out.println("Unsorted array:");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " : ");
}
System.out.println("\n\nSorted array:");
String sorted[] = GenericSortUtility.genericSorter(array);
for(int i = 0; i < array.length; i++) {
System.out.print(sorted[i]+ " : ");
}

System.out.println("\n\nUnsorted List:");
System.out.println(list.toString());
GenericSortUtility.genericListSorter(sortedList);
System.out.println("\nSorted List:");
System.out.println(sortedList.toString());

System.out.println("\nSorted List from Collections.sort():");
Collections.sort(colSorted);
System.out.println(colSorted.toString());

System.out.println("\nBut does it work for other objects?");
System.out.println("Unsorted Integer list:\n" + intList.toString());
GenericSortUtility.genericListSorter(intList);
System.out.println("\nSorted int list?");
System.out.println(intList.toString());
}
}

dlorde
March 13th, 2009, 09:55 AM
Collections are often preferable to arrays, so I'm OK with that, but can you explain why you're using a a wildcard instantiation with a lower bound, i.e. <E extends Comparable<? super E>> in the genericSorter and genericListSorter methods?

The outcome of any serious research can only be to make two questions grow where only one grew before...
T. Veblen

ProgramThis
March 13th, 2009, 10:19 AM
Because when I took his code and added mine I forgot about your comment that Comparable<E> would work just as well :blush:

Good exercise for me. I want to take the SCJP exam sometime and I really really need to get up to speed on this stuff.

dlorde
March 13th, 2009, 11:58 AM
I really really need to get up to speed on this stuff.The Generics FAQ (http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) link is very good, as are these two: Going Wild With Generics 1 (http://www.ibm.com/developerworks/java/library/j-jtp04298.html?S_TACT=105AGX02&S_CMP=EDU), Going Wild With Generics 2 (http://www.ibm.com/developerworks/java/library/j-jtp07018.html?S_TACT=105AGX02&S_CMP=EDU).

Who dares to teach must never cease to learn...
J.C. Dana

ProgramThis
March 13th, 2009, 12:20 PM
Great links, thanks! :thumb: