java - How to pass array of objects in a method as the object array is defined privately in another class -


first class

public class student { private int roll; private string name; } //getter & setter methods both 

second class

public class studentdata { private student s [] = new student[3]; public void addstudent(student s[]) { //method add student data  public class teststudent { public static void main(string[] args) {     studentdata sd = new studentdata();     sd.addstudent(**what should passed parametet here??**); 

how arguments passed in sd.addstudent(?)

i can see studentdata contain 3 object maximum. offer use list instead. in case class this:

public final class studentdata {     private final map<string, student> students = new hashmap<>();      public void addstudents(student[] students) {         if (students != null && students.length > 0)             (student student : students)                 addstudent(student);     }      public void addstudent(student student) {         if (student != null)             students.put(student.getname(), student);     } } 

add whole array studentdata brakes incapsulation. have accept array , add each element separately (see example above).

anyway add methods studentdata need: single elemnts, add element; collection or array, add elements separately ineratingh through collection.

p.s. example (only example) without collection:

public final class studentdata {     private final student[] students;     private int pos;      public studentdata(int max) {         students = new student[max];     }      public void addstudents(student[] students) {         if (students != null && students.length > 0)             (student student : students)                 addstudent(student);     }      public void addstudent(student student) {         if (student != null) {             if (pos >= students.length) {                 // array full             } else {                 students[pos++] = student;             }         }     } } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -