LinkedList Java遍历和打印
如果您能帮助回答以下问题,我将不胜感激:
我已经使用Java以非常标准的方式创建了一个自定义链接列表。以下是我的课程:
public class Node { private Object obj;
private Node next;
public Node(Object obj){
this(obj,null);
}
public Node(Object obj,Node n){
this.obj = obj;
next = n;
}
public void setData(Object obj){
this.obj = obj;
}
public void setNext(Node n){
next = n;
}
public Object getData(){
return obj;
}
public Node getNext(){
return next;
}
}
public class linkedList {
private Node head;
public linkedList(){
head = null;
}
public void setHead(Node n){
head = n;
}
public Node getHead(){
return head;
}
public void add(Object obj){
if(getHead() == null){
Node tmp = new Node(obj);
tmp.setNext(getHead());
setHead(tmp);
}else{
add(getHead(),obj);
}
}
private void add(Node cur,Object obj){
if(cur.getNext() == null){
Node tmp = new Node(obj);
tmp.setNext(cur.getNext());
cur.setNext(tmp);
}else{
add(cur.getNext(),obj);
}
}
}
我试图打印值我已经插入到列表如下
public static void main(String[] args) { // TODO code application logic here
Node l = new Node("ant");
Node rat = new Node("rat");
Node bat = new Node("bat");
Node hrs = new Node("hrs");
linkedList lst = new linkedList();
lst.add(l);
lst.add(rat);
lst.add(bat);
lst.add(hrs);
Node tmp = lst.getHead();
while(tmp != null){
System.out.println(tmp.getData());
tmp = tmp.getNext();
}
}
但是我从IDE获得的输出是
linklist.Node@137bd6a1linklist.Node@2747ee05
linklist.Node@635b9e68
linklist.Node@13fcf0ce
为什么打印出引用,而不打印出诸如bat,ant,rat …之类的字符串的实际值?
如果我想打印出实际值,那该怎么办?
非常感谢你
回答:
您的linkedList
课程已经Node
为您创建了!
linkedList list = new linkedList();list.add("foo");
list.add("bar");
Node tmp = lst.getHead();
while(tmp != null){
System.out.println(tmp.getData());
tmp = tmp.getNext();
}
将打印
foobar
以上是 LinkedList Java遍历和打印 的全部内容, 来源链接: utcz.com/qa/419864.html