Why does print toString()
doesn't print Array Class member objects? It says "cannot return a void result". What type of result does it want when my ArrayList private objects contain values.
Eg: In Person
class-
public class Person {
private ArrayList <String> name;
private ArrayList <Integer> number;
public Person(ArrayList <String> thatName, ArrayList <Integer> thatNumber)
{
name = new ArrayList <String>(thatName);
number = new ArrayList <Integer>(thatNumber);
}
public ArrayList<String> getName()
{
return name;
}
public ArrayList<Integer> getNumber()
{
return number;
}
public String toString()
{
return System.out.println(name + "" + number); //Gives error "cannot return a void result"
}
Also, can I make String.format(,)
work in this case? I tried, but it doesn't work as the ArrayList object types are not primitive data types.
EDIT:
Here is how I am calling Person
class but toString()
not printing anything.
import java.util.ArrayList;
public class PersonTest {
public static void main(String[] args) {
ArrayList <String> nam = new ArrayList <String>();
ArrayList <Integer> numb = new ArrayList <Integer>();
nam.add("Zeus");
numb.add(99);
Person pr = new Person(nam, numb);
pr.toString();
}
}
System.out.println is a void, therefore can't return anything. What you should do is :
public String toString()
{
return name + " " + number;
}
and in the caller, use person instance to print :
System.out.println(person.toString());
or below, since printing an object will automatically invoke the toString() method.
System.out.println(person);