tags:

views:

155

answers:

5

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?

+2  A: 

Yes, 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)

Bozho
A: 
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.

Yatendra Goel
+3  A: 

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.

Dominik
Why not just call toString() on the list directly?
Adamski
@Adamski: The interface List does not define a contract for toString().
Dominik
+2  A: 

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.

Adamski
How can you be sure the output will look like this? List is just an interface and there is no contract about the output of the toString() method in List.
Dominik
@Dominik: It's a fair point but I would guess that in 99.9% of cases people tend to use the JDK implementations of List, which do produce this style of output. I tend to use this output for debug logging but would never rely on it for presentation-level logic.
Adamski
+2  A: 

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, " ; ");
romaintaz