class Person {
public String firstname;
public String lastname;
}
Person p1 = new Person("Jim","Green");
Person p2 = new Person("Tony","White");
ArrayList<Person> people = new ArrayList<Person>();
people.add(p1);
people.add(p2);
System.out.println(people.toString());
I have to override class Person’s ToString method so that p1.toString() yields Green, Jim. As a result, the output of the code above will be [Green, Jim,White, Tony] which is not desirable. It would be easier for text processing programs if the output is, for example [Green, Jim&White, Tony]. The default delimiter needs to be replaced by other symbols such as &. What is the simplest way to achieve that if there is any?
Why do you need to do this with the toString method?
I would suggest that you pass your list to a customized formatter class of your own making. However, if you insist, I think that one alternative is that you extend ArrayList and override the toString method only.
One choice could be to let the Person class itself deal with the complexity of formatting the collection of items of its own type:
Then you could simply do something like:
Output is:
[Kenobi, Obi-wan& Skywalker, Luke]But this is just an idea. I am pretty sure there are many other ways to do it.