Reputation:
Why is this wrong? I can't use add, I am not sure how to. Some java documentation says I need to have add(index,data) but others are just add(data) and the compiler is support that as well. It is having an error with my data type.
import java.util.*;
public class graph1 {
public static void main (String[] args){
ArrayList<Node> web = new ArrayList<Node>();
web.add(0, "google", new int[]{1,2});
}
}
Node.java:
public class Node {
int i;
String title;
int[] links;
Node(int i, String title, int[] links){
this.i = i;
this.title = title;
this.links = links;
}
}
Upvotes: 2
Views: 2064
Reputation: 8207
Your custom class has to be instantiated in order to add it to the ArrayList. To do this, use web.add(new Node(0, "google", new int[]{1,2}));
.
In your case, you used web.add(0, "google", new int[]{1,2});
, which java compiler understood as you were trying to add 3 object at once, thus compiler complained that something is wrong with your code.
Also, you should consider implementing (overriding) custom compare(o1, o2) if you'll need to sort the array, because the default Collections.sort(list) doesn't know how to correctly order your objects.
Upvotes: -1
Reputation: 244
You need to make the node like this
Node node = new Node(i, title, links);
web.add(node);
Upvotes: 2
Reputation: 2562
You have an arraylist of Nodes, but are trying to add a bunch of random variables. You need to use those variables to make a Node and then add that.
web.add(new Node(0, "google", new int[]{1,2}));
Upvotes: 1
Reputation: 285403
You're forgetting to include new Node(...)
inside of the ArrayList's add(...)
method since you're not adding the combination of an int, a String and an array of int to the ArrayList, but rather you're adding a Node object. To do this, the Node object must be explicitly created and then added:
web.add(new Node(0, "google", new int[]{1,2}));
Upvotes: 4