从内部类引用的局部变量必须是final或有效的final错误显示在以下代码中:
public Vector<Map<String, Object>> newsFeedConnection(String var, Hashtable punishment) {
ConnectionRequest connectionRequest;
connectionRequest = new ConnectionRequest() {
@Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
results = p.parse(new InputStreamReader(input));
punishment = (Hashtable) results.get("punishment");
}
}
}
但是当我更改将其更改为final(下面的代码)时,它再次给出“无法为最终变量惩罚分配值”错误。
public Vector<Map<String, Object>> newsFeedConnection(String var, final Hashtable punishment) {
ConnectionRequest connectionRequest;
connectionRequest = new ConnectionRequest() {
@Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
results = p.parse(new InputStreamReader(input));
punishment = (Hashtable) results.get("punishment");
}
}
}
如果设置全局变量,则无法从其他类的方法访问该值。
按值传递与按引用传递-传递对象引用时,您正在执行按引用传递。这样做时,可以通过在对象上调用适当的方法来更改对象的状态,但不能更改对象本身的引用。例如:
public class TestPassByReference {
public static void main(String[] args){
StringBuilder stringBuilder = new StringBuilder("Lets Test!");
changeStringDoesNotWork(stringBuilder);
System.out.println(stringBuilder.toString());
changeString(stringBuilder);
System.out.println(stringBuilder.toString());
}
static void changeString(StringBuilder stringBuilder){
stringBuilder.append(" Yeah I did it!");
}
static void changeStringDoesNotWork(StringBuilder stringBuilder){
stringBuilder = new StringBuilder("This will not work!");
}
}
输出:
Lets Test! //Value did not change
Lets Test! Yeah I did it!
我希望现在您可以与此基本方面相互冲突,以解决不正确的情况。
但是,您可以执行以下操作:
HashTable tempHashTable = (Hashtable) results.get("punishment");
punishment.clear();
punishment.putAll(tempHashTable);
还有为什么要使用HashTable?有更好的线程安全集合类可以提供更好的性能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句