2013-01-21 130 views
0

我有一个泛型类应该创建一个数组中存储的可比较集合。可比公司和仿制药的工作方式我很不清楚。添加到泛型集合

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;  
    } 
} 

首先,什么样的集合是收集(排列,列表等)。它永远不会显式实例化为新的Array [],所以我很好奇它应该如何创建一个数组。其次,需要一种插入指定值(用于测试目的,我已经使用'5')并将其分配给集合[0]的方法。但是,当我返回集合[0]时,它返回为空。这里是插入方法:

public void insert(T x) 
{ 
    collection[0] = x; 
} 

没什么特别的。我将非常感谢一些澄清,为什么收集返回null,以及我应该如何去增加指定x价值的集合。

+0

你可以看看[ArrayList的代码](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/例如ArrayList.java#ArrayList。%3Cinit%3E%28int%29) - 等价构造函数确实:'collection = new Object [capacity];'。通用部分在其他方法中。例如:'public T get(int index)' – assylias

回答

1

正常约定是:

private T[] collection; 

此致是一个C兼容性语法。

public void add(T x) { 
    if (size >= collection.length) 
     throw new IllegalStateException(); 
    collection[size] = x; 
    ++size; 
} 

集合是任何类型集合的接口。实现类是HashTree,ArrayList等。

这是与其他一些语言的区别,即java没有像JavaScript这样的少数“集合”类,但有一些接口,有一个可以选择的实现。所以你必须为Map选择HashMap,TreeMap,LinkedHashMap等等。所以在API中你放置了接口,但是实现使用了一些实现的技术优势。

例如遍历TreeMap是按键排序的。遍历LinkedHashMap按照插入顺序排序。

关于null必须是编程错误。

+0

这对我有用。返回null的问题必须与我试图从中检索值。 – hanoldaa

1

超出问题集合是什么(看起来在API中),你发布的代码工作得很好。用一些内置的类来实现Comparable(比如Integer或String)......你可以发布调用insert()方法的代码吗?

+0

我基本上只是实现了System.out.println(oc.collection [index]);来自主驱动程序类,但我不得不调用OrderedCollections类中的方法来返回值。现在我只需要计算我将用什么方法对集合进行排序... =/ – hanoldaa

+0

只需调用Arrays.sort(collection),但要确保在集合中没有任何空值(或检查compareTo中的空值)在你的对象实例化的类中实现)。 – fazhool

+0

“但要确保你没有任何内藏的空洞”,这解释了它。我之前尝试过,但在填写集合之前尝试对其进行排序。非常感谢帮助=) – hanoldaa