Home > Back-end >  How to correctly create method accepting list of objects
How to correctly create method accepting list of objects

Time:01-07

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.

CodePudding user response:

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) {

CodePudding user response:

You use public static <T> String formatList(List<T> listToFormat,int indentationSize){ to accept objects instead.

Code:

public static <T> String formatList(List<T> 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));
    }
  •  Tags:  
  • Related