Reputation: 616
I have a generic class that should creates a collection of comparables stored in an array. I am very unclear on the way that comparables and generics work.
public class OrderedCollection<T extends Comparable<? super T>>
{
private T collection[]; // the collection
private int size, tempValue; // how many elements currently stored
/**
* Constructor allocates array and initializes size
* @param size the number of elements stored
*/
public OrderedCollection (int capacity)
{
collection = (T[]) new Comparable[capacity];
size = 0;
}
}
First of all, what kind of collection is collection (array, list etc). It is never explicitly instantiated as new Array[] so I am curious how this is supposed to create an array.
Second, there needs to be a method that inserts a designated value (for testing purposes I have been using'5') and assigning it to collection[0]. However, when I return collection[0], it returns as null. Here is the insert method:
public void insert(T x)
{
collection[0] = x;
}
Nothing fancy. I would greatly appreciate some clarification as to why the collection returns null and how I should go about adding the designated x value to the collection.
Upvotes: 0
Views: 184
Reputation: 121
beyond the question what a Collection is (look that up in the API), the code you posted works just fine. Test it with some built in classes that implement Comparable (like Integer or String)... could you post the code that calls the insert() method?
Upvotes: 1
Reputation: 109547
The normal convention is:
private T[] collection;
Yours was a C compatibility syntax.
public void add(T x) {
if (size >= collection.length)
throw new IllegalStateException();
collection[size] = x;
++size;
}
Collection is an interface for any kind of collection. Implementing classes are HashTree, ArrayList etcetera.
This is a difference to some other languages, that java has not a few "collection" classes like JavaScript, but a few interfaces, that have an implementation you can choose. So you have for a Map the choice of HashMap, TreeMap, LinkedHashMap and so on. So in the API you put the interface, but the implementation uses the technical advantages of some implementation.
For instance traversing a TreeMap is ordered by the keys. Traversal of a LinkedHashMap is ordered by the order of insertion.
That about null must be a programming error.
Upvotes: 1