Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make method accept List which contains objects of any datatype

Tags:

java

My goal is to check the type of messages and then accordingly convert them to Strings and add them. How can I achieve this?

public void addMessages(List<?> messages) {
    if (messages != null) {
        if (messages instanceof String) {
            for (String message : messages) {
                this.messages.add(message);
            }
        }
    }

    else {
        for (Object message:messages) {
            this.messages.add(String.valueOf(message));
        }
    }
}
like image 206
lesnar Avatar asked Jul 29 '15 06:07

lesnar


People also ask

Can a list contain any type of object?

Lists can contain any arbitrary objects. List elements can be accessed by index. Lists can be nested to arbitrary depth.

Can a Java list contains different types?

You can add any Java object to a List . If the List is not typed, using Java Generics, then you can even mix objects of different types (classes) in the same List . Mixing objects of different types in the same List is not often done in practice, however.


1 Answers

You can just pass in a List of Objects - you don't even need the if/else since you can just always call "toString()" or "String.valueOf" on the message object:

public void addMessages(List<Object> messages) {
    if (!CollectionUtils.isEmpty(messages)) {
        for (Object message : messages) {
            this.messages.add(String.valueOf(message));
        }
    }
}

On a side note: Potential problems could arise from having null elements in the messages list - so you might want to check for that in your loop. Other potential pitfalls are:

  • this.messages is not initialised and adding messages throws a NullPointerException
  • if this is a method of a singleton (e.g. a spring service) working with instance variables should be avoided
like image 134
nutfox Avatar answered Sep 27 '22 00:09

nutfox