0

I have a homework where I created 2 classes. TeamMember and ProjectTeam. However I have a problem with creating an empty array of type TeamMember.

class TeamMember {
   protected String name;
   protected ProjectTeam team;
   TeamMember(String newName, ProjectTeam newTeam){
       name = newName;
       team = newTeam;
}
class ProjectTeam {
   protected String name;
   protected TeamMember[] members;
   public ProjectTeam(String newName){
       name = newName;
       members = help here;
}
public class Main {
 public static void main(String[] args) {
    ProjectTeam team1 = new ProjectTeam("team1");
    TeamMember peter = new TeamMember("Peter", team1);
    System.out.println(peter.name);
    System.out.println(team1.members);
}

}

What I am trying to do is to create a TeamMember and pass it to a ProjectTeam. However I cant seem to find a way how to pass an empty array of type Team Member in construcor of ProjectTeam. Any feedback would be appreciated.

tuto108
  • 25
  • 5
  • 3
    When you create an array, you specify its length, which cannot be changed later. If you create an empty array (length 0), it will always stay empty, so perhaps that's not what you need. Perhaps an ArrayList will be more useful. – Eran Mar 16 '20 at 11:17
  • why do you need an empty array? get an array or at least an int for array size – Majid Roustaei Mar 16 '20 at 11:18
  • What Eran says. You almost certainly want a `List` like an `ArrayList` instead of an array. – MC Emperor Mar 16 '20 at 11:19
  • @MajidRoustaei we are specifically asked to create an empty array in our assignment – tuto108 Mar 16 '20 at 11:20

2 Answers2

1

As the comments say, maybe you should model this differently, especially if you need to add/remove elements, but here is how you create a zero-length array. Sometimes, rarely, you need that. It's the same as any other length:

String[] myArray = new String[0];

Alternatively:

String[] myArray = new String[]{};   // empty array initializer
kutschkem
  • 6,194
  • 3
  • 16
  • 43
  • @tuto108 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java – kutschkem Mar 16 '20 at 11:39
0

try to used ArrayList to the connection between the TeamMember and ProjectTeam

    class TeamMember {
       protected String name;
       protected ProjectTeam team;
       TeamMember(String newName, ProjectTeam newTeam){
           name = this.newName;
           team = this.newTeam;
    }
    class ProjectTeam {
       protected String name;
       protected ArrayList <TeamMember> members;
       public ProjectTeam(String newName,ArrayList<TeamMember>members){
           name = this.newName;
           members =this.members;
    }
        ProjectTeam team1 = new ProjectTeam("team1");
ArrayList<ProjectTeam> traems=new ArrayList<ProjectTeam>();
traems.add(team1)

check the code I don't know if it works fine or not

Mohammed_Alreai
  • 856
  • 6
  • 11