- Joined
- Feb 12, 2010
- Messages
- 1
- Reaction score
- 0
[SOLVED] Sorting an ArrayList
Hey, guys. I have a homework assignment due later tonight and am having a bit of trouble. I have to sort an array list as part of the assignment. My understanding is that must use Collections.sort, but I can't get that to work. I am not sure if that is due to my use of generics or what. Here is my current code.
and the error messages I am getting are:
I've looked at quite a few explanations of sorting arraylists, and they all achieve sorting with Collections.sort( ArrayList );, but this isn't working for me. They all used string values for sorting and I am using numbers, but it seems like Collections.sort would be able to sort values of the Number type. Any help would be great. Let me know if I left out something you need to know.
Hey, guys. I have a homework assignment due later tonight and am having a bit of trouble. I have to sort an array list as part of the assignment. My understanding is that must use Collections.sort, but I can't get that to work. I am not sure if that is due to my use of generics or what. Here is my current code.
Code:
import java.util.ArrayList;
import java.util.Collections;
//create generic MyList class with type parameter T
final class MyList<T extends Number>{
//create ArrayList of type T
ArrayList<T> list = new ArrayList<T>();
//create an add method that adds argument of type T to ArrayList
public void add( T new_element ){
list.add( new_element );
}
//create method 'largest' that returns largest value of 'list'
public T largest(){
Collections.sort( list );
//must return largest value after sorting
}
//create method 'smallest' that returns smallest value of 'list'
public T smallest(){
Collections.sort( list );
//must return smallest value after sorting
}
}
public final class GenericsHW{
public static void main(final String[] args) {
MyList<Number> list = new MyList<Number>();
list.add( new Integer( 10 ) );
list.add( new Double( 1.2 ) );
}
}
and the error messages I am getting are:
Code:
/MyDev/java/HW3/GenericsHW.java
/MyDev/java/HW3/GenericsHW.java:30: cannot find symbol
symbol : method sort(java.util.ArrayList<T>)
location: class java.util.Collections
Collections.sort( list );
^
MyDev/java/HW3/GenericsHW.java:36: cannot find symbol
symbol : method sort(java.util.ArrayList<T>)
location: class java.util.Collections
Collections.sort( list );
^
I've looked at quite a few explanations of sorting arraylists, and they all achieve sorting with Collections.sort( ArrayList );, but this isn't working for me. They all used string values for sorting and I am using numbers, but it seems like Collections.sort would be able to sort values of the Number type. Any help would be great. Let me know if I left out something you need to know.
Last edited: