[Solved] Calling methods on a List object of type Class [closed]


Some Background

It not exactly clear what your asking… but it sounds like you want to know why you can’t call the methods defined in MessageHandler from your list test of type List<MessageHandler>.

The definition of List<E> in the javadoc explains that the parameter E is the type that the list can contain. The add(E e) method, for example, will inherit from this and only allow items of type E to be added to the list. What this does not mean is that you can call the methods defined within class E from the List<E> object.

For example, I would not be able write this (where .getRGB() is a method from the Color Class):

 List<Color> colorList = new ArrayList<>;
 colorList.getRGB();

However I would be able to write this. Notice how I added a Color object to the list and am getting it from the list to call the method on it:

 List<Color> colorList = new ArrayList<>;
 colorList.add(Color.Red);

 colorList.get(0).getRGB();

To Answer Your Question

What this means for you, then, is that you should not call your .storeMessage(...) and .getRecentMessage(...) on your list test. Rather you should be creating an object of type MessageHandler, calling your store method on that, and then adding it to the list. Once you’ve done that you can loop over the list again, get each object from the list, and output the message.

Try this:

int desktopID = 0;
Random randomID = new Random();

// Note that I'm instantiating the list before using it!
List<MessageHandler> test = new Arraylist<>;

for(int i = 0; i < 1000; i++){
    desktopID = randomID.nextInt(10);
    System.out.println(desktopID);

    // Create a MessageHandler object and set the message.
    MessageHandler handler = new MessageHandler();
    handler.storeMessage("Message Number: "+ i, desktopID);        

    // Add that method to your list
    test.add(handler);
}

// This is a foreach loop. Very useful! Will iterate over each element in order.
for(MessageHandler handler : test){
    System.out.println(handler.getRecentMessage(desktopID).toString());
}

(I’ve assumed that your MessageHandler object has a default constructor.)

2

solved Calling methods on a List object of type Class [closed]