mohammad javad Jafari
mohammad javad Jafari

Reputation: 35

NullPointerException for List<T> variable in Anylogic

I am trying to model peer influence for churn situations. Agents will send messages to their peers depending on different conditions. I have also created a List called MessagesReceived to store received messages.(The number of these messages may be >1).

Variable declaration

Inside the Agent's Connections>Communications>OnMessageReceived , I have added this.Messages_Recieved.add(msg); which should add the received message to the list.

Now I get a NullPointerException Error on onReceive method of my agent.

Upvotes: 0

Views: 61

Answers (2)

Felipe
Felipe

Reputation: 9376

first, you have a collections object in the agents palette that you can use instead of this, you can check the collection class options to select LinkedList

enter image description here

but if you insist in using a variable to define the list, you need to initialize it like this::

linkedlist

Upvotes: 1

mohammad javad Jafari
mohammad javad Jafari

Reputation: 35

The system works fine and processes the message but when it tries to add the new message to the list, it encounters the NullPointerException as the list does not exist yet. Declaring a List as variable is not enough. We need to initiate it too: List<String> myList = new LinkedList<String>(); I have been able to initiate this variable inside Agent>Properties>Agent Actions>On StartUp : Messages_Recieved = new LinkedList<String>();

Also note that we cannot initiate a List in java using List<String> myList = new List<String>();

List is generic and you can create different collections (ordered/unordered) depending on the class you are using: See here for more information. I have used LinkedList in this example.

Upvotes: 1

Related Questions