我编写了一个用于按功能更改列表值的代码:
package test3;
import unit4.collectionsLib.*;
public class main {
public static void change (Node<Integer>first) {
first = new Node<Integer>(12,first);
}
public static void main(String[] args) {
Node<Integer> first = new Node<Integer>(1);
first = new Node<Integer>(2,first);
first = new Node<Integer>(3,first);
Node<Integer> pos = first;
while (pos!=null) {
System.out.print(pos.getInfo()+"->");
pos = pos.getNext();
}
System.out.println();
change(first);
pos = first;
while (pos!=null) {
System.out.print(pos.getInfo()+"->");
pos = pos.getNext();
}
}
}
输出是:
3->2->1->
3->2->1->
如何传递函数中的对象以更改列表?
答案 0 :(得分:0)
Java总是按值传递,但你可以这样做。
public class main {
public static Node<Integer> change(Node<Integer> first)
{
return new Node<Integer>(12,first);
}
public static void main(String[] args) {
Node<Integer> first = new Node<Integer>(1);
first = new Node<Integer>(2,first);
first = new Node<Integer>(3,first);
Node <Integer>pos = first;
while (pos!=null){
System.out.print(pos.getInfo()+"->");
pos = pos.getNext();
}
System.out.println();
pos = change(first);
while (pos!=null){
System.out.print(pos.getInfo()+"->");
pos = pos.getNext();
}
}
}