Why does change one variable also change another?
The code has 3 class as following
Code:
import java.util.*;
import java.awt.*;
public class AList {
public static void main(String[] args)
{
String s1,s2,s3;
s1="a";s3="b";
s2=s1;
System.out.println(s2);
s2=s3;
System.out.println(s1);
GList g = new GList();
g.add("Luke");
}
}
Code:
public class GList<E>
{
private static class Node<E>
{
public E data;
public Node<E> next;
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
public E get()
{
return this.data;
}
}
private Node<E> head;
public GList()
{
head = new Node<E>(null, null);
}
public void add(E e)
{
Node<E> c=head;
while ( c.next!=null)
c=c.next;
Node<E> newNode=new Node<E>(e, null);
c.next=newNode;
}
}
After s2=s3, s2 contains "b". s1 still has "a". But after
c.next=newNode, head.next is not null and contains newNode.
Why? Thank you.