Add & Show data in Java ArrayList [closed]
- by Kaidul Islam Sazal
I have a class inside a main class :
static class Graph{
static int u, v, cost;
}
I have instantiated an arraylist of the class:
static List<Graph> g = new ArrayList<Graph>();
And I insert several values into the arraylist like this:
Scanner input = new Scanner(System.in);
for (int i = 0; i < edge_no; i++) {
Graph e = new Graph();
e.u = input.nextInt();
e.v = input.nextInt();
e.cost = input.nextInt();
g.add(e);
}
And I print it like this:
for (int i = 0; i < edge_no; i++) {
System.out.println(g.get(i).u + " " + g.get(i).v + " " + g.get(i).cost);
}
But the problem is that, when I print it, only the last value is shown all the time.It seems that, all the previous values are over-written with it.
Input :
1 2 5
1 3 8
2 3 9
Output:
2 3 9
2 3 9
2 3 9
Expected output is just like the input.But I can't fix the problem as I am novice in java.