Reputation: 7
I want to pass array as a parameter of object but I am kind of stack. So here is my problem.
public class Publisher {
public static void main(String args[]) {
String teachers[] = {"Jyothi", "Jyostna", "Sumathi"};
Publisher2 p1 = new Publisher2(teachers[1],20); //The problem is here, I can't specify
//index of array (I can put onlu teachers without index[1])so toString method is returning address of object instead of the name
System.out.println(p1);
}
}
class Publisher2 {
String[] teachers;
int y;
public Publisher2(String[] teachers, int y) {
this.teachers = teachers;
this.y = y;
}
@Override
public String toString() {
return "Publisher2{" + "teachers=" + teachers + ", y=" + y + '}';
}
}
Upvotes: 0
Views: 85
Reputation: 1906
Since you have clarified your question in various comments (please edit your question), we now know that you want to pass a single item, but you have implied in code and comments that Publisher2
must be constructed with an array as a parameter.
Therefore, you will need to build a new array containing the single item.
String[] teacherSubset = new String[] { teachers[1] };
Publisher2 p1 = new Publisher2(teacherSubset, 20);
or...
Publisher2 p1 = new Publisher2(new String[] { teachers[1] }, 20);
Please edit your question so that it is clear about exactly what you are trying to accomplish.
Upvotes: 0
Reputation: 589
Another possibility would be to use varargs and swap the parameters (the varargs have to be the last in the parameter list):
public Publisher2(int y, String... teachers) {
this.teachers = teachers;
this.y = y;
}
With this approach you can pass as many arguments (none, a single, multiple or an array):
new Publisher2(20);
new Publisher2(20, teachers[0]);
new Publisher2(20, teachers);
With the toString
problem you can use java.util.Arrays
, so that the toString
looks like this:
@Override
public String toString() {
return "Publisher2{" + "teachers=" + Arrays.toString(teachers) + ", y=" + y + "}";
}
The strings then will look like
Publisher2{teachers=[], y=20} // for new Publisher(20)
Publisher2{teachers=[Jyostna], y=20} // for new Publisher(20, teachers[1])
Publisher2{teachers=[Jyothi, Jyostna, Sumathi], y=20}
// for new Publisher(20, teachers)
Upvotes: 0
Reputation: 201409
teachers[1]
is the second element in your array. The array itself is just teachers
. Like,
Publisher2 p1 = new Publisher2(teachers, 20);
Upvotes: 2