设计在数组中存储可比较对象的泛型类



我正在尝试弄清楚如何将tst.insert((和tsttxt.insert((的值存储到数组中。到目前为止,我唯一能做的就是让程序认识到它们在那里。当我尝试打印变量时,我得到了 tst.insert(( 的最后一个值。我假设显示最后一个值是因为其他值被覆盖。

public class genericdrive {
public static void main(String[] args) {
    collection<Integer> tst = new collection<>();
    collection<String> tsttxt = new collection<>();
    //System.out.println("If collection is empty return true: " + tst.isEmpty());
    tst.insert(45);
    tst.insert(43);
    tst.insert(90);
    tsttxt.insert("Jeff");
    tsttxt.insert("Rey");
  }
}

..

public class collection<T> extends genericdrive {
private T element;
private T[]array;
// collection<T> objt = new collection<>();
public void set(T element) {
    this.element = element;
}
public T get() {
    return element;
}
public <T> void insert(T i) {
    i = (T) element;
    //array[0]=<T> i;
}
}
考虑到

array变量包含您编写的插入函数的所有元素,不会将任何值推入其中。

如果私有变量应为数组,则这是一种解决方法。

请尝试以下操作:

public class MyCollection<T> {
  private T element;
  private T[] array;
  MyCollection(){
     array = (T[]) Array.newInstance( Comparable.class , 0); 
  }
  public void set(T element) {
     this.element = element;
  }
  public T get() {
    return element;
  }
  public void insert(T i) {

     T[] temp = (T[])  Array.newInstance(array.getClass().getComponentType(), array.length + 1);
     temp[array.length] = i;
     System.arraycopy(array, 0, temp, 0, array.length);
     array = temp;
  }
}

最新更新