这是我在此的头一篇博文。我最近开始对学习 Java 产生兴趣,我阅读了一些初级教程,将http://docs.oracle.com作为我的书签并阅读了一些示例代码。
现在搞乱我自己的练习,我发现了一些奇怪的东西,我在手册/教程/文档中找不到任何令人满意的答案。
我制作了一个小课程来练习 IO 和队列样式对象。它旨在创建一个包含文件名和空链表的对象。然后它有一种方法可以读取给定文件,并将其中的行一一添加到链表队列中。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
public class Handle
{
public File filehandle;
public LinkedList<String> queue;
Handle (File filename)
{
filehandle=filename;
LinkedList<String> queue = new LinkedList<String>();
}
public void addq()
{
try{
FileReader ava;
ava = new FileReader(filehandle);
//without initializing new linekedlist queue it'll give NPE in queue.add
//why can't it use class/instance variable queue it does fine with filehandle
queue = new LinkedList<String>();
BufferedReader br = null;
String sCurrentLine;
br = new BufferedReader(ava);
while ((sCurrentLine = br.readLine()) != null)
{
queue.add(sCurrentLine);
}
queue.offer("POISON");
}
catch (IOException e) {e.printStackTrace();}
}
奇怪的事情 - 当试图使用在类中声明的类变量/实例变量队列(公共 LinkedList 队列)时,该队列也在构造函数中启动,在方法内部,它编译得很好,但在运行时它在 queue.add 行中抛出了 NPE。当我在方法中初始化方法变量队列时,NPE 消失了。为什么方法不能添加到类变量队列中?似乎使用 fielhandle 变量就好了!同样如 poll 方法导致代码运行类(将其发布)所示 - 它似乎实际上仍然将行添加到实例变量队列中,而不仅仅是临时方法变量。(这当然很好,但我不明白如何以及为什么)下面是我用来运行 Handle 类的代码。
import java.io.File;
import java.util.LinkedList;
class Runner
{
public static void main(String[] args)
{
File file = new File("proovidest.csv");
Handle handle =new Handle(file);
//using the constructor, now we have object with filehandle and empty queue variables
handle.addq();
String mison;
//so apparently the instance variable queue is still filled with lines (good)
//but how? the method had to delcare its own variable (why), but still the class field is //now filled? how?
while ((mison = handle.queue.poll()) != "POISON")
{System.out.println(mison);}
}
}
所以谁能给我很好的解释为什么我不能在运行时的方法中访问类变量队列,尽管我能够使用文件句柄变量。那我应该怎么做才能访问它?任何人都可以告诉我类字段队列是如何被填充的,尽管我在方法中声明了一个新变量。还是 handle.queue.poll 以某种方式检测变量形式的方法?