lesnar
lesnar

Reputation: 2480

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

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));
        }
    }
}

Upvotes: 7

Views: 6459

Answers (4)

Ganesh Kumar
Ganesh Kumar

Reputation: 3240

This is just an enhancement over the answers by nutfox.

public void addMessages(List<?> messages) {
        List<String> collect = messages.stream().map(i -> String.valueOf(i)).collect(Collectors.toList());
        this.messages.addAll(collect);
}

Upvotes: 2

Loganathan Mohanraj
Loganathan Mohanraj

Reputation: 1874

You can achieve that with "Java Generics".

The Messages object initialized in the main method below will accept the list of objects of any type. You can initialize Messages object with a specific type as well.

public class Messages<T> {

    private List<T> messages = new ArrayList<T>();

    public void addMessages(List<T> messages) {
        for (T message : messages) {
            // Use String.valueOf or message.toString() 
            // if you would like to convert the objects to String.
        }
    }

    public static void main(String[] args) {
        Messages<Object> msg = new Messages<Object>();
        msg.addMessages(/** Your List of objects of any type **/);
    }

}

Upvotes: 1

nutfox
nutfox

Reputation: 484

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

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

public void addMessages(List<Object> messages) {

That is just enough where messages hold all type of Objects.

Upvotes: 1

Related Questions