I am trying to create a class that creates arrays for a project of mean I have been killing my self on how to do it
public class Team {
private Object arr;
void createTeam(){
String[] arr = new String[15];
}
}
I am trying to create a class that creates arrays for a project of mean I have been killing my self on how to do it
public class Team {
private Object arr;
void createTeam(){
String[] arr = new String[15];
}
}
Just after creating the array using new
assign it to the arr
reference if you
want to use arr
in Team
class
public class Team {
private String[] arr;
void createTeam() {
arr = new String[15];
}
}
, if you want to call createTeam
from another class and use like
public class Team {
public static String[] createTeam() {
return new String[15];
}
}
Usage from another class
String[] arr = Team.createTeam();
Let me straighten out a bit of terminology - the class contains one or more methods; I think you want a method to create an array when called.
It would be most useful if, after the array is created, it was returned to the caller; since you talk of doing this more than once, it makes sense for the caller to do it as many times as it wants:
public class Team {
pubilc String[] createTeam() {
String[] arr = new String[15];
return arr;
}
}
Now some other piece of code can do this:
...
Team team = new Team();
String[] teamArray = team.createTeam();
and teamArray has been created and returned to the caller for whatever it wants it for. Note that, in this case, no copy of the team variable exists in the Team object once the createTeam()
method has returned.
Actually, if you want to access your newly created array from another class you simply can't, because your String[] is a private attribute and your package scoped method does return a void.
If you only need to create a String[] for other classes, then you don't need the attribute "arr", you could also overload your method to create an array of desired size:
public class Team {
public static String[] createTeam(){ return new String[15]; }
public static String[] createTeam(int n){ return new String[n]; }
}
If you need your String[] for a further manipulation in your "Team" class, then you should keep it private and use a getter to access it from other classes :
public class Team {
private String[] arr;
public void createTeam(){ this.arr = new String[15]; }
public String[] getArr() { return arr; }
}
if you're trying to cast a String[] into your arr attribute, your method doesn't work because Java considers String[] arr in the method as a local variable and not as class attribute, then you should remove "String[]" before arr.