Java 设计在数组中存储可比较项的泛型类
我试图找出如何将tst.insert和tsttxt.insert的值存储到数组中。到目前为止,我所能做的唯一一件事就是让程序认识到他们在那里。当我试图打印变量时,我得到了tst.insert的最后一个值。我假设显示最后一个值,因为其他值正在被覆盖Java 设计在数组中存储可比较项的泛型类,java,generics,Java,Generics,我试图找出如何将tst.insert和tsttxt.insert的值存储到数组中。到目前为止,我所能做的唯一一件事就是让程序认识到他们在那里。当我试图打印变量时,我得到了tst.insert的最后一个值。我假设显示最后一个值,因为其他值正在被覆盖 public class genericdrive { public static void main(String[] args) { collection<Integer> tst = new collection<>
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 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;
}
}
我认为Java类名约定是以大写字母开头?您想做什么?insertT i实际上什么都不做。如果要存储结果,请使用ArrayList或某种形式的集合来存放项目。另外,当genericdrive没有可继承的内容时,为什么要扩展它?代码中有多个错误:1个大写字母代表类名。2当集合只有一个main方法时,为什么要扩展genericdrive?3插入方法设置其输入@Zachary我被要求不要使用arrayList。我试了一些东西,但发帖时忘了拿出来this@RaghuVarmaManthena请记住,数组在声明时具有固定的大小。在这种情况下,您永远不会实例化数组,但即使您已经实例化了数组,如果您尝试插入超出初始声明大小的内容,也需要增加大小。有人要求我不要使用数组列表。有没有办法将元素插入到数组中?@RaghuVarmaManthena调整数组大小是另一个已经讨论过的问题question@RaghuVarmaManthena检查编辑的帖子。没有使用ArrayList。
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;
}
}