How to declare a dynamic object array in Java?

后端 未结 4 1109
一整个雨季
一整个雨季 2020-12-31 02:23

I want to ask a question about Java. I have a user-defined object class, student, which have 2 data members, name and id. And in another class, I have to declare that object

相关标签:
4条回答
  • 2020-12-31 03:20

    Its not possible,we need to specify the size of array when declaring object array;

    1. one way to declare object array

       student st[];
       st=new student[3];
      
    2. second way

       student st[]=new student[5];
      

    in both cases not any objects are created only the space is allocated for the array.

    st=new student[1];
    

    this will create a new object;

    0 讨论(0)
  • 2020-12-31 03:21

    You could declare as: Student stu[]=null;, and create it with fixed size: stu[]=new Student[10] until you could know the size. If you have to use array.

    0 讨论(0)
  • 2020-12-31 03:26

    User ArrayList instead. It'll expand automatically as you add new elements. Later you can convert it to array, if you need.

    As another option (not sure what exactly you want), you can declare Object[] field and not initialize it immediately.

    0 讨论(0)
  • 2020-12-31 03:26

    As you have probably figured out by now, regular arrays in Java are of fixed size (an array's size cannot be changed), so in order to add items dynamically to an array, you need a resizable array. In Java, resizable arrays are implemented as the ArrayList class (java.util.ArrayList). A simple example of its use:

    import java.util.ArrayList;
    
    // Adds a student to the student array list.
    ArrayList<Student> students = new ArrayList<Student>();
    students.add(new Student());
    

    The <Student> brackets (a feature called generics in Java) are optional; however, you should use them. Basically they restrict the type of object that you can store in the array list, so you don't end up storing String objects in an array full of Integer objects.

    0 讨论(0)
提交回复
热议问题