0

MailBox Class

public class MailBox {

        ArrayList<TwootMessage> messages = new ArrayList<TwootMessage>();

        public void addMessage(TwootMessage message){

            if(messages.size() < 100){

                messages.add(message);
                Collections.sort(messages);
            }

            else{

                System.out.println("The Mailbox is full, cant add more messages, sorry!");
            }
        }

        public void deleteMessage(int messageIndex){

            messages.remove(messageIndex);

        }

        public TwootMessage getFirstMessage(){

            return messages.get(0);
        }
    }

This is my code. I am trying to be able to create two types of mailbox from this class one that only accept TextTwoot and one that accept everything. TwoootMessage is the superclass for textTwoot and some other type of twoots. Can anyone please offer some help? Thank you

1 Answer 1

1

Make the class generic:

public class MailBox<T> {

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

    public void addMesssage(T message) {
        //implementation goes here.
    }

    public T getFirstMessage() {
        return messages.get(0);
    }
}

This will let you create objects like:

MailBox<TwoootMessage> twootMessageMailbox = new MailBox<TwoootMessage>();
MailBox<Object> mailBoxForEverything = new MailBox<Object>();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but what <T> stands for and how to make the objects to be different from one another when actually creating them?
T stands for a generic type. Read more: here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.