java - 在java中设置构造函数和一些对象

标签 java arrays

所以我有一个名为 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/

相关文章:

java - 为什么我的 Spring @Autowired 字段为空?

java - 使用 Chef 安装 Tomcat-8

python - 零维 numpy.ndarray : only element is a 2D array : how to access it?

java - 在 @Table(name = "tableName") - 使 "tableName"成为 JPA 中的变量

java - ArchUnit 测试敏感变量命名

c++ - 如何在类中有一个二维数组作为私有(private)变量,然后在构造函数中设置

arrays - 零和最小子数组

子数组的Java长度

JavaScript — 数组被一堆 "undefined"填满

java - 我如何与 mac 雪豹上的 java 更新作斗争