Trying to keep track of how many objects I create

Hello everyone I'm trying to keep track of how many message objects I created and Assign them to a data member.
Right now it assigns all the Message objects the same number at the end which is 3. I wanted it to assign 1 to the first object it create, 2 for the 2nd, and 3 for the 3rd.
here's a small version of my code:
package ss;
import java.util.ArrayList;
import java.util.Iterator;
public class MainTest {
     public static void main(String [] args)
          Message msg = null;
          ArrayList<Message> msgList = new ArrayList<Message>();
          for(int i = 0; i < 3; i++)
               msg = new Message();
               msgList.add(msg);
          System.out.println(msgList);
package ss;
//this class will hold the Event/Message
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Set;
import java.util.Iterator;
public class Message {
     //these are datamembers that will be used during
     //the sending of the message to the reciever
     //PacketID should be incremented each time a new message is created
     static int PacketID = 0;
     Message()
          PacketID +=1;
     public String toString() {
          return("PacketID: " + this.PacketID
                    + "\n");
}output:
[PacketID: 3
, PacketID: 3
, PacketID: 3
Any ideas what I'm doing wrong?
Thanks!

Thanks BigDaddyLovehandles,
Well there's the problem, I just posted a simpler problem to a bigger one. So I am keeping them in a collection as you can see below.
I'm keeping these message stored in a multi map, and it is multi-threaded. Everytime a user connects to my server I create a new thread, and start adding the "messages" to the database.
But I must have a packetID, meaning every new message created I need to assign that number to the message object.
I also see a problem with this like you said, its not thread safe, if 2 clients connect to the server, and both send me events, there are going to be 2 different maps, copying events from the client and storing them in their own seperate databases.
This might not be a problem because after I get the events on each thread, i send them to another server for processing.
Here's an example of what my database looks like that stores the messages:
//this class should store all the Messages or "Events" and
//you can access them based on their Serial key.
public class MessageDB {
     //database to hold the information
     //     holds the Alerts/messages
     Map<String, List<Message>> AlertMap;
     //Constructor
     MessageDB() {
          AlertMap = new HashMap<String, List<Message>>();
     //print, outputs the contents of the hashMap
     public void print() {
          //want to print out the Key and all the Messages
          //associated with that key
          //print, outputs the contents of the hashMap
               for (String key : AlertMap.keySet())
                    System.out.println("\n\nSerial (key): " + key
                              + "\nValues in Map: \n" + AlertMap.get(key));
     void add(Message msg) {
          //getting the position of the List by EntityID if avaiable
          List<Message> AlertList = AlertMap.get(msg.Serial);
          //checking to see if there is a unique Key already in the Map.
          if (AlertList == null) {
               //if there isnt a key in the map, add a new key, and a new List mapping
               //to the key EntityID;
               AlertList = new ArrayList<Message>();
               AlertMap.put(msg.Serial, AlertList);
               AlertList.add(msg);
          } else {
               //adding message to List
               AlertList.add(msg);
     }Any suggestions on what I can to number all these messages and it will be thread safe?

Similar Messages

  • How do I keep track of how many times a method is called inside anthr clas?

    I am writing code for a program that solves a Knight's Tour. A Knight's Tour is a path a Knight Chess piece can take around the board starting at any spot, touching every square once, and only once. I have to write 2 classes and one is provided. The provided class is encrypted and written by our professor. All I know that it does is simulates the game using the two classes I write and provides a print out and prompts to ask the user which square they want to move to next.
    The square class I have to write consists of a constructor that makes a square object that keeps track of its color (white/black) and its status (whether it has been visited, is occupied by the knight, or is free and has not be visited).
    The GameBoard class I have to write is what I am having problems with. I am writing a method that determines how many squares have been visited. The previous mentioned class that my professor wrote for me contains a method moveKnight();. The way the program works is that every time moveKnight() is called a square's status is changed to occupied and therefore visited later. moveKnight() will only work if the move requested by the user is a valid move.
    SO! My main problem (sorry for all the explaining, just trying to give you all the information) is that I don't know how to keep track of how many times moveKnight() is called by the program. If i can figure this out it should be simple. I'm new to java but i believe...
    if(moveKnight() is called)
    {count++;} //count is a member variable already initialized
    return count;
    the moveKnight() is called section within the if() statement is what I am unclear how to do. Please help.
    Thanks, Veritas

    in your case you want 'count' to be a class attribute rather than a local variable. But yes, incrementing it each time that the method is called will serve your purpose.

  • How to keep track of how many records to display in a page.

    Hi All:
    I am using Weblogic 9.2, Web Services Client, and Struts.
    I have a java client in struts that calls a web services.
    The "ID" field contains a Java integer.
    The "First_Name" is a Java String.
    The "Effective_Date" field is a Java date field.
    The web service returns an arrayList of a class called Result.
    Code for Result.java:
    >
    public class Result
    int id;
    String first_Name;
    Date effective_Date;
    public int getId
    return id;
    public void setId(int id)
    this.id=id;
    public String getFirst_Name()
    return first_Name;
    public void setFirst_Name(String first_Name)
    this.first_Name = first_Name;
    public Date getEffective_Date()
         return effective_Date;
    public void setEffective_Date(Date effective_Date)
         this.effective_Date=effective_Date;
    From the arrayList, I displayed the result as the following:
    ID FIRST_NAME EFFECTIVE_DATE
    3 John 9/10/2007
    2 Andrew 1/11/2006
    5 Peter 3/4/2006
    The "ID" header is a link.
    The "First Name" header is a link.
    The "EFFECTIVE_Date" is a link.
    If I clicked on the link "ID", the first time, it will sort the rows in ascending
    order like the following:
    ID FIRST_NAME EFFECTIVE_DATE
    2 Andrew 1/11/2006
    3 John 9/10/2007
    5 Peter 3/4/2006
    If I clicked on the link "ID", the second time, it will sort the rows in descending
    order like the following:
    ID FIRST_NAME EFFECTIVE_DATE
    5 Peter 3/4/2006
    3 John 9/10/2007
    2 Andrew 1/11/2006
    If I clicked on the "First_Name" field the first time, it will sort the rows in
    desceding order.
    If I clicked on the "First_Name" field the second time, it will sort the rows in
    ascending order.
    This applies the same for the "EFFECTIVE_DATE".
    If the arrayList returns 80 records of class Results.java.
    I needed to displayed only the first 50 records for the first page and 30 records for the second page.
    How do I keep track of that so that when I am in the second page, I know to display only record 51 to 80?
    If I have a arrayList that returns 120 records of class Results.java.
    In the first page, it displayed only 50 records.
    In the second page, it displayed only 50 records.
    In the third page, it displayed only 20 records.
    Assuming I am able to sort the rows by ID, FirstName and Effective_Date by using Results.java implementing the
    Java Comparator class. Is it still possible to keep track of how many records displayed in the first page and how many records should
    be dispalyed in the second page?
    Any hint would be greatly appreciate.
    Yours,
    Frustrated.

    Hi,
    Access the table through SM30. It comes blank as standard. Click "New Entries" and make entries for changes to be tracked. For example, whenever an org. unit changes 002 and 003 relationship, you will make entries like:
    01 O 1001 B002 Activate box checked
    01 O 1001 B003 Activate box checked
    Here, 01 is your active plan version, O is org. unit, 1001 is infotype and B002 and B003 are the subtypes. You can also use * for infotype and subtype which means every change will be logged.
    If you then run the report RHCDOC_DISPLAY through SA38, it will pick up all the changes pertaining to B002 and B003 relationship for org. units (in the above example).
    Similarly, you can set up this table for other object types.
    For more information, follow SPRO>Personnel Management>OM>Basic Settings>Activate change documents and go through the documentation for that node. Also, read up the documentation for the report.
    Hope this helps.
    Donnie

  • How to keep track of how many times a link has been clicked?

    How to keep track of how many times a link has been clicked or accessed? Do I need to use database for this?

    Hi
    Proably something like this can work,
    1> Have a servlet/bean invoked when the link is linked
    2> have a static variable in that servlet/bean wich gets incremented before the control is passed to another desired page..
    The problem with this approach is that care has to be taken that the servlet/bean is not re-instalised, in case of which the static variable will also be instalised and the data would be lost.
    The best thing is to store the count in the database.
    Regards
    Arathi.

  • How many Objects are created in this?

    Hi,
    How many objects are created in the flwg code:
    String str = new String("Hello");
    String str2 = "Hey there";
    str = str + str2;

    Depends if you're counting objects created at compile time.
    "Hello" is created at compile time. That's 1.
    new String("Hello") creates a new String object at runtime, pointing its backing array at the "Hello" in the constant pool. That's 2.
    "Hey there" is created at compile time. 3.
    str + str2 I might do everything at compile time, or it might do some at runtime. I don't know if str is considered a compile time literal here. I think not, but I'm not sure. You can check by using javap. If I'm correct, then at runtime you'll create a StringBuffer (4) and another String (5).
    So I'd say 5 objects. But if the compiler treats str as a literal and therefore can do the str+str2 at compile time, then it might do so without creating the StringBuffer. Or it might still create it at compile time, use it, and throw it out.

  • How many objects are created?

    I have this question which some one posted to me.
    He asked me how many objects are created when an object of a simple class is created for example
    class A{
    public static void main(String args[])
    A a1 = new A();
    Now how many objects are created? I think only one. Can anyone tell me if any other objects are also created.
    Plz tell me .

    No, the answer is indeed 1. All the other objects
    (including the String[] in the main method
    parameters) are created outside of the A
    class, either by the JVM itself or by some other
    class that calls the A.main() method. You can try
    this out for yourself by adding a constructor such as
    A()
    System.out.println("Creating class A");
    } and see what prints out.Take a closer look at the question:
    how many objects are created when an object of a
    simple class is created for exampleIt doesn't say "how many objects of type A are created".
    I.e. The VM has to load class A before you can create an object from it, and thus an object of type Class is created. There are also a bunch of other objects which needs to be created before you can instantiate A.
    Kaj

  • Garbage Collection: how many objects are created after for loop?

    Please see the fallowing java code
    1 public class Test1 {
    2     
    3     public static void main(String[] args) {
    4          
    5          MyObj obj = null;
    6          for(int i=0;i<5;i++){
    7               obj = new MyObj();
    8          }
    9 // do something
    10
    11     }
    12 }
    so my question is How may objects are eligible for garbage collection at line no: 9 (// do something)?

    so my question is How may objects are eligible for
    garbage collection at line no: 9 (// do something)?It's impossible to answer that question since we don't know how MyObj is implemented.
    Kaj

  • Keeping count of how many times a case structure has been entered.

    I have a "Case" structure (when a button is pressed, it is "case True").
    I want to keep track of how many times this "case True" has been entered.
    How can I do this?
    Solved!
    Go to Solution.

    For that you need to have a shift register or a feedback node and keep counting whenever the case structure case is executed the count will be increased by one see the attached snippet.
    Good Luck
    The best solution is the one you find it by yourself
    Attachments:
    CaseStructure count.png ‏10 KB

  • How many String are created?

    public String makinStrings() {
         String s = �Fred�;
         s = s + �47�;
         s = s.substring(2, 5);
         s = s.toUpperCase();
         return s.toString();
    }How many objects are created when this method is called?
    My answer is 5
    1. "Fred"
    2. "47"
    3. "Fred47"
    4. "ed4"
    5. "ED4"
    But my friend is telling it is 3.
    1. "Fred"
    2. "47"
    3. "Fred47"
    I know that any method called on String object creates a brand new String. Please help me with the solution whether it is 3 or 5.

    hi,
    First of all i want to thanks for all of your replies.
    My friend is saying that when we say "How many objects when method is invoked" it means at runtime. String literals are not created at run time.
    String s = �Fred�; // No object is creatd here
    s = s + �47�; // One object created "s"
    s = s.substring(2, 5); //Another object "s"
    s = s.toUpperCase(); //Another object "s"
    return s.toString();
    Hence total 3 objects.
    Now the i have got a doubt. Are String literals created at Complie time itself. Or since String s = "Fred" is a compile time constant field. And String literal "47" is also a compile time constant field.
    Suppose if the code is like this
    String s = new String("Fred")
    String s1 = s; ---------------- Then is this String object created at Run time.
    String s2 = "47" ----------- This object is created at Complie time.
    Please clarify my doubt.

  • In query, how many objects can include in structure

    Hi expert,
    In BEX query coloum, How many objects can include in structure.

    Hi Sunil,
    We can include maximum of 999 fields in one structure.
    http://help.sap.com/saphelp_nw04/helpdata/en/4d/e2bebb41da1d42917100471b364efa/frameset.htm
    Regards,
    Venkatesh

  • How many Objects created??

    Hi Friends,
    I am really confused with this question,can someone please tell me how many objects would be created by the following code??My answer is two("java" on the heap and the normal new String() Object),am i right???
    public class Objects{  
    public static void main(String[] args)    {   
        String one = "Java";    
        String two = "Java";   
        String three = "J" + "a" + "v" + "a"; 
        String four = new String("Test");  
    }Thanks

    Probably not, since all the operands are string
    literals. The compiler probably sees that and instead
    generates the same bytecode that it would have if it
    had been coded as: "Java" in the first place. But
    again, still stupid and pointless.just what i wanted to say but was a bit slow. maybe it's stupid and pointless,
    but for grins, i am attaching the constants pool from the class file that was
    obtained by compiling the code in post 1 with Sun's compiler. I don't see any
    "J" or "a" or .........
    pool index: 1 type: 10 class index: 7 name index: 16 value: null
    pool index: 2 type: 8 class index: -1 name index: 17 value: null
    pool index: 3 type: 7 class index: -1 name index: 18 value: null
    pool index: 4 type: 8 class index: -1 name index: 19 value: null
    pool index: 5 type: 10 class index: 3 name index: 20 value: null
    pool index: 6 type: 7 class index: -1 name index: 21 value: null
    pool index: 7 type: 7 class index: -1 name index: 22 value: null
    pool index: 8 type: 1 class index: -1 name index: -1 value: <init>
    pool index: 9 type: 1 class index: -1 name index: -1 value: ()V
    pool index: 10 type: 1 class index: -1 name index: -1 value: Code
    pool index: 11 type: 1 class index: -1 name index: -1 value: LineNumberTable
    pool index: 12 type: 1 class index: -1 name index: -1 value: main
    pool index: 13 type: 1 class index: -1 name index: -1 value: ([Ljava/lang/String;)V
    pool index: 14 type: 1 class index: -1 name index: -1 value: SourceFile
    pool index: 15 type: 1 class index: -1 name index: -1 value: Objects.java
    pool index: 16 type: 12 class index: 9 name index: 8 value: null
    pool index: 17 type: 1 class index: -1 name index: -1 value: Java
    pool index: 18 type: 1 class index: -1 name index: -1 value: java/lang/String
    pool index: 19 type: 1 class index: -1 name index: -1 value: Test
    pool index: 20 type: 12 class index: 23 name index: 8 value: null
    pool index: 21 type: 1 class index: -1 name index: -1 value: Objects
    pool index: 22 type: 1 class index: -1 name index: -1 value: java/lang/Object
    pool index: 23 type: 1 class index: -1 name index: -1 value: (Ljava/lang/String;)Vwalker

  • I need to know how many objects i got selected

    Hi all,
    I need to know how many objects i got selected for a particular issue and ussualy are too many to count one by one. I know that this information is provided in other software like Corel or Freehand, but I didn't find out how to get this info in Illustrator.
    Any idea?
    Thanks

    Open the Document Info palette.
    From its flyout menu, turn on Selection Only and Objects.
    The palette will not remember those settings. You have to re-select them every time you relaunch Illustrator.
    The Document Info palette is a half-baked hack, tagged-on to display a subset of the information in the normally-hidden programmer's window, instead of incorporating the data properly into the program's interface. So it's another completely unintuitive grab-bag of important information that everyone needs, but no one would expect to look for there.
    JET

  • How Many Objects Are Selected

    How can I tell how many objects are selected when I draw a selection marque around multiple objects?

    Open the Document Info Palette.
    Find its secret little flyout menu.
    Select from that menu "Objects".
    Let go.
    Then go to that same menu all over again and select "Selection Only".
    Scroll through the list and sum the quantities shown. Except be careful not to include the count of "All Text Objects" with the counts of "Point Type Objects", "Area Type Objects", and "Type On A Path Objects".
    Repeat those steps every time you start a new work session in AI, because AI's palettes can't remember the way you set them between launches.
    How could you have overlooked that intuitive and straightforward routine?
    JET

  • Seing how many objects are selected.

    Hi! I'm having a problem seing how many objects are selected when I navigate in Finder's windows. In Snow Leopard, there used to be a grey bar at the bottom telling you these infos, but this seems to be gone in Lion. Anyone knows how to get it back?
    Thank you!

    Open the Document Info Palette.
    Find its secret little flyout menu.
    Select from that menu "Objects".
    Let go.
    Then go to that same menu all over again and select "Selection Only".
    Scroll through the list and sum the quantities shown. Except be careful not to include the count of "All Text Objects" with the counts of "Point Type Objects", "Area Type Objects", and "Type On A Path Objects".
    Repeat those steps every time you start a new work session in AI, because AI's palettes can't remember the way you set them between launches.
    How could you have overlooked that intuitive and straightforward routine?
    JET

  • How many objects will be created due to constructor chaining

    Consider this case
    ChildClass obj = new ParentClass();
    I would like to know how many objects will be created in this process.

    Consider this case
    ChildClass obj = new ParentClass();
    I would like to know how many objects will be created
    in this processThe simple answer is one.
    The complex answer is many.
    In terms only of the classes that your code represents conceptually there will be one.
    The reality is that the the object itself might create objects. And loading the classes, if it has not already occurred will also create objects.

Maybe you are looking for

  • Dual monitors with macbook closed

    i am running dual monitors with Macbook Pro and would like for my Macbook to be closed.  How do I change that setting?

  • T400 with Windows XP, freezes on shutdown

    Hi, I recently purchased a Lenovo T400 laptop (originally with vista) and installed Windows XP on it. I installed all the drivers one by one from the lenovo website, and verything works nicely- except for one hitch. When I go to shutdown or restart,

  • Count in Answers

    Hi, I have two columns example Project and Chnaged-Date, I want to get the total, count of rows. How can I do it in ANswers, without modifying my database? Thank you for your time and help.

  • Introduction of R12 look and feel

    I built jsp pages using adf components on jdev 10.1.3 I tried to introduce the swan look and feel by makin an xss sheet in WEB-INF/lib/META-INF/adf/styles directory I was able to change the background colors but couldnt change the look of commandbutt

  • Click checkbox, subform prints

    So here I am again with a bell and whistle request. I am not a programmer, so if someone were to help me, I'll need some hand holding. I have a 5 page form with lots of endorsements on it.  Each Endorsement starts with a checkbox.  Each endorsement i