Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly create method accepting list of objects

Hi I would like to create method which accepts list of Object something like this:

public static String formatList(List<Object> listToFormat,int indentationSize){
        String indentation = Stream.generate(()->"\t").limit(indentationSize).collect(Collectors.joining());
        String newIndentedLine = "\n"+indentation;
        return newIndentedLine+listToFormat.stream()
                .map(Object::toString)
                .collect(Collectors.joining(newIndentedLine));
    }

but when I try to do something like this:

List<Car> cars = new ArrayList<>();
...
Formater.formatList(cars);

it is not allowed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Java doesn’t allow this because a List<Car> is not a List<Object> even though a Car is an Object.

It’s not necessary to declare a type parameter, because we don’t care what the type actually is. Every reference type descends from Object which has a toString method, so we can just replace List<Object> with List<?>:

public static String formatList(List<?> listToFormat, int indentationSize) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading