So I have an empty list like so
List<Node> nodes = null;
and then I want to add "Node"s into it
try {
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
while (true){
String first= scanner.next();
if (first.equals("-1")){
break;
}
Node node1= new Node(first, first);
if (nodes==null){
nodes.add(node1);
}
if (nodes!=null){
if(nodes.contains(node1)){
nodes.add(node1);
}
}
So obviously doing .contains in a null list gives me an exception error, but why does doing
if (nodes==null){
nodes.add(node1);
}
also gives me a null pointer error? It seems like empty lists are immutable. How can I still keep a List structure and still build it up from empty?
To append to an empty string in python we have to use “+” operator to append in a empty string.
In Python, an empty list can be created by just writing square brackets i.e. []. If no arguments are provided in the square brackets [], then it returns an empty list i.e.
List<Node> nodes = null;
This is not an empty list, this is a list reference which is iniitalized to null. You want rather:
List<Node> nodes = new LinkedList<Node>();
or similar. This gives you an empty list.
EDIT: After the change of question, this logic is completely messed up:
Node node1= new Node(first, first);
if (nodes==null){
nodes.add(node1);
}
if (nodes!=null){
if(nodes.contains(node1)){
nodes.add(node1);
}
}
What you're saying here is that if nodes == null (which it is now not), then try to add the node to the list. If it is not null, and node1 is already in the list (which it is not), then add it to the list. You can replace the lines above with:
if (!nodes.contains(node1)) {
nodes.add(node1);
}
which says if the node doesn't exist in the list, add it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With