MehtabC
MehtabC

Reputation: 50

Arraylist of Custom Object

This is a fairly simple question, but I am a beginner and I've been stuck on this part for hours now. I am not looking for an easy way out, but instead I just want to understand what is happening to my code and why it isn't working. My problem was:

Create a node class with a random number and the current time. Create a storage class and store those nodes in a list/array. Use the main class to create 50 nodes and display.

When I run it 50 times and get my list, I made the list print out the time so that I could check to see if my code was running, and they all have the same time. It means that different nodes aren't being stored into my list, and are instead being wiped out each time the loop runs. Why is that?

My code is attached:

Main:

public class NodeSort {

public static void main(String[] args) 
{
    int c = 0;
    while (c < 50)
    {
        Storage.add();
        c++; 
    }


}

}

Node:

public class Node
{
public static int num;
public static long time;

public Node()
{
    num = Random.getNum();
    time = System.nanoTime();
}

public static long getTime()
{
    return time;
}

public static int getNum()
{
    return num;
}
}

Storage:

public class Storage 
{
public static ArrayList<Node> list = new ArrayList<>();

public static void add()
{

    list.add(new Node());

}

When I do get time for x = 1-50, it prints out the same time 50 times instead of 50 different ones.

Upvotes: 0

Views: 104

Answers (1)

MattPutnam
MattPutnam

Reputation: 3017

They all have the same time value because they're all getting created at almost the same time. System.nanoTime() doesn't guarantee that you'll actually get nanosecond precision, it's up to the operating system's ability to discern time. Most OSes can only provide millisecond resolution. So if all of the calls happen within the same millisecond, you'll get the same values.

As far as the random number is concerned, I don't know--what is the Random class? It's not java.util.Random.

Edit: Oh wait, I see it. You declared num and time as static in your Node class. That means there's only one copy of each in existence. Just remove static from those declarations, and from the methods that return the values.

Upvotes: 4

Related Questions