所以我有一个名为 memoryStructure 的类,它应该代表名为 Student 的对象的支持结构,该对象具有名字、姓氏、年龄和大学。
这是麻烦的部分:
public class MemoryStructure {
private Student[] memoryArray;
private int currentSize;
private int arraySize;
// constructor goes here
/**
* Adds the object <code>student</code> to the collection right after the
* last element in the current collection.
*
* @param student
* Object to be added to the collection.
*/
public void add(Student student) {
// to be done
有人至少可以解释一下我应该在这里写什么吗? 这是我第一次接触 Java,遇到了一些麻烦。
此外,是否应该将学生作为另一个类,使用其构造函数和 setter / getter 来通过上面类中的内存数组进行更改?
一旦当前数组大小大于 arraySize,我还应该创建新数组,它应该是 2*arraySize 并复制前一个数组中的所有元素。这也放入构造函数中吗?
我希望这个问题不要太宽泛。
最佳答案
如果您不限于使用数组,那么 epoch 使用列表的答案实际上是更好的方法。不管怎样,我希望我不会因为发布代码而破坏学习语言的乐趣。
它应该看起来像这样
public void add(Student student) {
// assuming currentSize = 0 and arraySize = *something* in the constructor and that memoryArray = new Student[*something*]
if(currentSize == arraySize){
arraySize = arraySize*2;
memoryArray = Arrays.copyOf(memoryArray, arraySize);
}
memoryArray[currentSize] = student;
currentSize++;
}
关于java - 在java中设置构造函数和一些对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22295466/