Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / May 2008

Tip: Looking for answers? Try searching our database.

CIAO, How can I sort an ArrayList<K> of Generic Types ?

Thread view: 
Giordano - 21 May 2008 14:38 GMT
"Ciao" (Hi) to everyone,
please can you tell me how can I sort an ArrayList<K> of generic
types ?

If this arraylist were of this kind, ArrayList<String>, I could sort
it simply using this instruction:

ArrayList<String> list = new ArrayList<String>();
java.util.Collections.sort ( list );

but, in my case, i see that i cannot sort in this same way when i use
an arraylist of generic types.. like this one:

ArrayList<K> list = new ArrayList<K>();
/* ERROR --> */ java.util.Collections.sort ( list );

/* ERROR --> */ javac myProva.java
.\myIndexedTreeMap.java:46: cannot find symbol
symbol  : method sort(java.util.ArrayList<K>)
location: class java.util.Collections
        Collections.sort (list);
                   ^
1 error

Thanks if you can give me any help for my question ?
Ciao
Andrew Thompson - 21 May 2008 15:11 GMT
import java.math.BigInteger;

class SortThis {

 public static void main(String[] args) {
   String string = "four";
   Integer integer = new Integer(4);
   BigInteger bigInteger = new BigInteger("4");

   // Which of string, integer and bigInteger
   // come 1st, 2nd and 3rd when sorted?

   // ..Why?
 }
}

--
Andrew T.
PhySci.org
Vivien Barousse - 21 May 2008 16:02 GMT
> "Ciao" (Hi) to everyone,
> please can you tell me how can I sort an ArrayList<K> of generic types ?
[quoted text clipped - 19 lines]
>
> Thanks if you can give me any help for my question ? Ciao

Hi,

Collections.sort is expecting a List containing objects implementing the
Comparable interface.

Did your K class implements Comparable ?

Hope this helps,

Vivien Barousse
Giordano - 21 May 2008 17:07 GMT
> Collections.sort is expecting a List containing objects implementing the
> Comparable interface.
>
> Did your K class implements Comparable ?

Thanks Vivien.. the K isn't a class, but the way to indicate a generic
type (so K could be an Integer, a String or any class you are using at
the moment).
However, at the end of the facts, in my case the K is always
equivalent to a String, so i decide to implement(?).. re-write
everything using the type String (I think that i could write a
comparator class that accept the generic K and then switch into the
right compare() method in the case this K were an Integer, a
Character, a String, etc.. etc...)

Thanks again Vivien
:)
Ciao
Lew - 22 May 2008 03:54 GMT
>> Collections.sort is expecting a List containing objects implementing the
>> Comparable interface.
[quoted text clipped - 4 lines]
> type (so K could be an Integer, a String or any class you are using at
> the moment).

That only works inside a generic definition that uses K as a type parameter.

Why don't you work up an SSCCE
http://sscce.org/
to show us the context in which you are attempting this.

> However, at the end of the facts, in my case the K is always
> equivalent to a String, so i decide to implement(?).. re-write
> everything using the type String (I think that i could write a
> comparator class that accept the generic K and then switch into the
> right compare() method in the case this K were an Integer, a
> Character, a String, etc.. etc...)

switch inside a class to handle type resolution is an antipattern.
Inheritance and polymorphism are the way to do that, not explicit type casts.

You need something like

public class Foo <T extends Comparable <? super T>>
{
  private List <T> stuff = new ArrayList <T> ();

  public List <T> getStuff()
  {
    return stuff;
  }

  public void sort()
  {
    Collections.sort( stuff );
  }
}

(Add the right imports to turn the above into an SSCCE.)

Then client code can do things like:

 Foo <Integer> foo = new Foo <Integer> ();
 List <Integer> stuff = foo.getStuff();
 addItemsTo( stuff );
 foo.sort();

You might have noticed that this adds nothing that List doesn't already have:

 List <Integer> stuff = new ArrayList <Integer> ();
 addItemsTo( stuff );
 Collections.sort( stuff );

In other words, List /already is/ how you can sort an array of generic type.

\--
Lew
Roedy Green - 23 May 2008 03:06 GMT
On Wed, 21 May 2008 06:38:06 -0700 (PDT), Giordano
<mejoro82@gmail.com> wrote, quoted or indirectly quoted someone who
said :

>"Ciao" (Hi) to everyone,
>please can you tell me how can I sort an ArrayList<K> of generic
[quoted text clipped - 11 lines]
>ArrayList<K> list = new ArrayList<K>();
>/* ERROR --> */ java.util.Collections.sort ( list );

see http://mindprod.com/jgloss/sort.html
http://mindprod.com/jgloss/comparable.html
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 23 May 2008 04:46 GMT
On Wed, 21 May 2008 06:38:06 -0700 (PDT), Giordano
<mejoro82@gmail.com> wrote, quoted or indirectly quoted someone who
said :

>ArrayList<K> list = new ArrayList<K>();
>/* ERROR --> */ java.util.Collections.sort ( list );

hint.  Look at the Javadoc for Collections.sort.

It says:

public static <T extends Comparable<? super T>> void sort(List<T>
list)

In other words T had bloody well better implement Comparable in a
generic way.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Lew - 23 May 2008 05:44 GMT
Giordano wrote, quoted or indirectly quoted someone who said :
>> ArrayList<K> list = new ArrayList<K>();
>> /* ERROR --> */ java.util.Collections.sort ( list );

> hint.  Look at the Javadoc for Collections.sort.
>
[quoted text clipped - 5 lines]
> In other words T had bloody well better implement Comparable in a
> generic way.

What do you mean by "implement Comparable in a generic way"?

Here's a prototypical use of Collections.sort(), with T = String,
output:

tangled: { first, last, always, never, maybe, }
 sorted: { always, first, last, maybe, never, }

<sscce name="SortOf.java">
package testit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortOf
{
  private static final String [] TANGLED = new String[]
       { "first", "last", "always", "never", "maybe", };

  static <T> void show( List <T> list )
  {
    System.out.print( "{ " );
    for ( T t : list )
    {
        System.out.print( t );
        System.out.print( ", " );
    }
    System.out.println( "}" );
  }

  public void demonstrate()
  {
    List<String> strangs = new ArrayList <String> ();
    strangs.addAll( Arrays.asList( TANGLED ));

    System.out.print( "tangled: " );
    show( strangs );

    Collections.sort( strangs );

    System.out.print( " sorted: " );
    show( strangs );
  }

  public static void main( String[] args )
  {
    (new SortOf()).demonstrate();
  }
}
</sscce>

Signature

Lew

Roedy Green - 23 May 2008 08:53 GMT
>What do you mean by "implement Comparable in a generic way"?

implement Comparable  == implements Comparable
implement Comparable in a generic way == implements Comparable< xxxx >
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Lew - 23 May 2008 13:14 GMT
>> What do you mean by "implement Comparable in a generic way"?
>
> implement Comparable  == implements Comparable
> implement Comparable in a generic way == implements Comparable< xxxx >

Aha.  So you mean

public class Foo implements Comparable <Foo>
{ ... }

If you leave off the "<Foo>" you get a raw type warning.

Signature

Lew

Roedy Green - 23 May 2008 19:12 GMT
>Aha.  So you mean
>
>public class Foo implements Comparable <Foo>
>{ ... }
>
>If you leave off the "<Foo>" you get a raw type warning.

Nearly always I just give a brief summary of what I explain at the
link, in this case
http://mindprod.com/jgloss/comparable.html
and
http://mindprod.com/jgloss/sort.html
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.