如果在changedetails()中将Employee引用设为null,则保留变量id值并且不抛出NullPointerException(代码1)可能是因为我们只传递了对象引用的副本,但在代码2中为什么变量值已更改
代码1:
public class JavaPassing {
public static void changedetails(Employee e)
{
e=null;
}
public static void main(String args[])
{
Employee emp = new Employee("Vishal",7);
changedetails(emp);
System.out.println(emp.id);
}
}
Run Code Online (Sandbox Code Playgroud)
代码2:
public class JavaPassing {
public static void changedetails(Employee e)
{
e.id=9;
}
public static void main(String args[])
{
Employee emp = new Employee("Vishal",7);
changedetails(emp);
System.out.println(emp.id);
}
}
Run Code Online (Sandbox Code Playgroud) 我写了以下代码:
public class HashMapImpl<Key,Value>{
Key key;
Value value;
List<? extends Key> keylist;
List<? extends Value> valuelist;
public HashMapImpl(Key k,Value v){
this.key = k;
this.value = v;
keylist = new ArrayList<Key>();
valuelist = new ArrayList<Value>();
}
public Value put(Key k, Value v){
this.keylist.add(k);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误add():
add(capture#3-of ? extends Key)类型中的方法List<capture#3-of ? extends Key>不适用于参数(Key)
为什么会这样?我该如何解决?