Why can't I call Collections.sort() on my ArrayList<T>?

26,363

Solution 1

There are basically 2 things that you need to look at :

Collections

From the Collections

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends

So basically if you have to sort or do any such kind of algorithms use this.

Next is :->

Collection

This is an interface that provides the basis of Java's collection framework. It does not include Map and Sorted Map. It represents a group of objects known as its elements and has implementations for concrete implementations. You need to think of this when you want to work with ArrayLists and Maps.

So, bottom line, you have a static algorithm to run which is present in Collections. So, use Collections.sort

Solution 2

You need to write Collections instead of Collection. They're related, but different. :-)

Solution 3

It's Collection**s**, not Collection:

vs.

Solution 4

It's Collections.sort() with an s.

import java.util.Collections and you should be fine.

Solution 5

Did you mean Collections.sort() (collections plural)?

Share:
26,363
Steve
Author by

Steve

Updated on July 09, 2022

Comments

  • Steve
    Steve almost 2 years

    For anyone who might have a question like this, you probably need "Collections.sort", not "Collection.sort", the mistake I made below.

    I have defined a class defined as

    public class Store implements Serializable, Comparable<Store> { ... }
    

    I have a field in another class defined as:

    ArrayList<Store> fStores = new ArrayList<Store>();
    

    I want to sort this collection, so in a method I call:

    Collection.sort(fStores);
    

    However, I get the following compilation error:

    The method sort(ArrayList<Store>) is undefined for the type Collection
    

    ArrayList implements List, and from the documentation:

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

    So, why do I get the error? I have also tried creating my own descendant of Comparator and passing that to the sort method with no luck.

    I'm guessing there's something about "< T extends Comparable< ? super T > >" I'm not understanding... ?

  • Steve
    Steve about 12 years
    Bingo! Thanks for the quick reply.
  • Ryan Amos
    Ryan Amos about 12 years
    @Steve Sure, sure. Happy to help :D