I would like to obtain the string text of the elements stored in a list, say List<Car>
. Would the toArray() and the toString() methods be the best options?
views:
155answers:
5Yes, but doing it manually gives you more control:
// initialize with the exact length
List<String> stringsList = new ArrayList<String>(listOfCard.size());
for (Car car : listOfCars) {
stringsList.add(car.toString());
}
If you haven't overridden the toString()
method and don't want to override id, you can use car.getName()
isntead of car.toString()
(or any property combination you like)
for (Car car : carsList) { // carsList is the object of List<Car>
System.out.println(car);
}
Note: The above will display the meaningful message only when you have overridden the toString() method of Car class.
e.g
public class Car {
private String carName;
....
....
public String toString() {
return carName;
}
}
The toString() method should be overridden to return meaningful information about the object in the string form.
In your case, I think the meaningful info would be all the details of the car. So overriding toString() method is best approach instead of using getCarName() or similar methods.
There is a static toString(Object[])
method an java.util.Arrays
. Calling it with the toArray()
result of the List (as you suggested) should do the job.
Providing you don't object to the string output following the convention:
[A, B, C]
... you can simply call the List
'stoString()
method to obtain your output (I'm not sure why people are advocating using a loop for this). It may also be sensible to override Car's toString()
method to return a human-friendly description of the object.
However, if you wish to obtain each element as an individual String
you will need to iterate over the List one element at a time.
Another idea is to use the Apache Commons Lang to write the following code:
StringUtils.join(myList);
The interest is that you also can provide a separator, for example:
StringUtils.join(myList, " ; ");