首页 \ 问答 \ LinkedList迭代异常(LinkedList Iteration Exception)

LinkedList迭代异常(LinkedList Iteration Exception)

我正在努力解决这个错误。 我觉得它很简单,但无法理解为什么会出错。

当我遍历链表中的值时,我不断收到NullPointerException

代码片段:

private void updateBuyBook(LimitOrder im) {

    LimitOrder lm = null;

    Iterator itr = buyBook.entrySet().iterator();

    boolean modify = false;

    while (itr.hasNext() && !modify) {

        Map.Entry pairs = (Map.Entry) itr.next();
        if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
            LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
                .getValue();
            ListIterator listIterator = orders.listIterator();
            while (listIterator.hasNext() && !modify) {
                LimitOrder order = (LimitOrder) listIterator.next();

                if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
                    lm = order;
                    addToBuyMap(im);
                    modify = true;
                    break;
                }
            }
            if (modify = true) {
                orders.remove(lm);
                break;
            }
        }
    }
}

错误在这一行:

Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));

请帮忙。 我的作业是否有任何错误? 请帮忙!!! 谢谢


I am struggling with this error. I feel its really simple but cannot understand why am getting the error.

I keep getting a NullPointerException when I iterate through values in my linked list.

Code Snippet:

private void updateBuyBook(LimitOrder im) {

    LimitOrder lm = null;

    Iterator itr = buyBook.entrySet().iterator();

    boolean modify = false;

    while (itr.hasNext() && !modify) {

        Map.Entry pairs = (Map.Entry) itr.next();
        if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
            LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
                .getValue();
            ListIterator listIterator = orders.listIterator();
            while (listIterator.hasNext() && !modify) {
                LimitOrder order = (LimitOrder) listIterator.next();

                if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
                    lm = order;
                    addToBuyMap(im);
                    modify = true;
                    break;
                }
            }
            if (modify = true) {
                orders.remove(lm);
                break;
            }
        }
    }
}

Error is at this line:

Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));

Please help. Is my assignment wrong in any way??? Please help!!! Thanks


原文:https://stackoverflow.com/questions/5255285
更新时间:2023-12-17 11:12

最满意答案

这里的问题是即使在-n 1模式下读取仍然是读取分隔线。 所以当它看到换行符时,它仍然认为是一个行分隔符并将其移除(并留下一个空变量)。

$ find_newlines() {
    while IFS= read -r -n 1 c; do
        declare -p c;
    done
}
$ printf 'a\nb' | find_newlines
declare -- c="a"
declare -- c=""
declare -- c="b"

正如Cyrus用bash 4.1+ ref所回答的,你可以使用-N标志来read以避免这个问题。

-N选项记录为(从Bash参考手册条目中read ):

-N nchars

在读取精确的nchars字符后读取返回值,而不是等待完整的输入行,除非遇到EOF或读取超时。 在输入中遇到的分隔符字符不会被专门处理,并且不会导致读取返回,直到读取nchars字符。

对于非4.1 +版本的bash(2.04+,看起来像),可以使用-d标志进行read以指定一个备用分隔符来解决此问题。 输入中不存在的任何分隔符都可以使用。 对于许多输入流而言,最可能的值可能是NUL / \0字符,您可以将其指定为-d ''read

$ find_newlines() {
    while IFS= read -d '' -r -n 1 c; do
        declare -p c;
    done
}
$ printf 'a\nb' | find_newlines
declare -- c="a"
declare -- c="
"
declare -- c="b"

The problem here is that read even in -n 1 mode is still reading delimited lines. So when it sees the newline it still considers that a line delimiter and removes it (and leaves you with an empty variable).

$ find_newlines() {
    while IFS= read -r -n 1 c; do
        declare -p c;
    done
}
$ printf 'a\nb' | find_newlines
declare -- c="a"
declare -- c=""
declare -- c="b"

As indicated in the answer by Cyrus with bash 4.1+(ref) you can use the -N flag to read to avoid this problem.

The -N option is documented as (from the Bash Reference Manual entry for read):

-N nchars

read returns after reading exactly nchars characters rather than waiting for a complete line of input, unless EOF is encountered or read times out. Delimiter characters encountered in the input are not treated specially and do not cause read to return until nchars characters are read.

For non-4.1+ versions of bash (2.04+ it looks like) you can use the -d flag to read to specify an alternate delimiter to work around this problem. Any delimiter that isn't going to exist in your input will work. The most likely value for that for many input streams is likely to be the NUL/\0 character which you can specify to read as -d ''.

$ find_newlines() {
    while IFS= read -d '' -r -n 1 c; do
        declare -p c;
    done
}
$ printf 'a\nb' | find_newlines
declare -- c="a"
declare -- c="
"
declare -- c="b"

相关问答

更多
  • 尝试添加(?s)内联标志启动模式的开始。 那将会. 匹配任何角色 Try adding the (?s) inline flag start the start of the pattern. That will make . match any character.
  • 您可以使用str.splitlines读取整个文件并分割行: temp = file.read().splitlines() 或者您可以手动剥离换行符: temp = [line[:-1] for line in file] 注意:最后一个解决方案仅在文件以换行符结尾时才起作用,否则最后一行将丢失一个字符。 在大多数情况下,这种假设是正确的(特别是对于由文本编辑器创建的文件,通常会添加结尾的换行符)。 如果您想避免这种情况,您可以在文件末尾添加换行符: with open(the_file, 'r+') ...
  • 我没有看到第一个选项存在真正的问题 - 如果您拥有buffer ,则可以修改它。 只是一些小问题: 正如Aaron指出的那样,如果文件的最后一行不以一个结尾(编辑:或者该行不适合缓冲区),那么fgets可能实际上不会返回换行符 - 所以您应该检查确实存在那里有一个换行符。 另外,我会在访问buffer[strlen(buffer)-1]之前检查strlen(buffer)>0 。 请注意,你的第二个选项有一个错误 - 它分配一个字节太少(你需要一个额外的字节为空字符)。 I see no real prob ...
  • >>运算符忽略空格,因此你永远不会得到换行符。 即使不允许类,也可以使用c-strings(字符数组): ifstream fin; char animal[64]; fin.open("Animals.dat"); while(fin >> animal) { cout << animal << endl; } 当从c字符串(上面是animal )中读取字符时,最后一个字符始终为0,有时表示为'\ 0'或NULL 。 这是在迭代单词中的字符时检查的内容。 例如: c = anim ...
  • 在sys.stdout.write(character)之后添加sys.stdout.flush() sys.stdout.write(character) 原因应该是stdout的输出被缓冲。 Add sys.stdout.flush() after sys.stdout.write(character) The reason should be that the output of stdout is buffered.
  • 你可以组合skipWhile和isEndOfLine (它们匹配\n和\r\n )。 使用lambda函数,您可以将它们组合到skipWhile谓词,该谓词跳过除换行符之外的任何空格。 skipSpaceNoNewline = skipWhile (\x -> isSpace_w8 x && not (isEndOfLine x)) You can combine skipWhile and isEndOfLine (which matches both \n and \r\n). Using a lam ...
  • 我正在考虑第一次尝试这个小改进: inoremap ( () inoremap (h () inoremap (l (); inoremap (" ("") inoremap (' ('') inoremap (; (); inoremap ) :call CloseChar()i inoremap [ [] inoremap [h [] inoremap ]
  • 当你做cValue = in.nextDouble(); ,它读取下一个标记(完整值)并将其解析为double。 如果此时按下了返回键, \n是要读取的缓冲区中的下一个标记。 当你这样做: String temp = in.nextLine(); ,它从前一个输入的缓冲区中读取\n ,并且charAt(0)失败,因为它只读取空(“”)字符串。 要解决此问题,可以通过添加in.nextLine()添加跳过前一个缓冲区,将\n \r添加为跳过模式,如下所示(这是Scanner.class定义的模式为LINE_S ...
  • 这里的问题是即使在-n 1模式下读取仍然是读取分隔线。 所以当它看到换行符时,它仍然认为是一个行分隔符并将其移除(并留下一个空变量)。 $ find_newlines() { while IFS= read -r -n 1 c; do declare -p c; done } $ printf 'a\nb' | find_newlines declare -- c="a" declare -- c="" declare -- c="b" 正如Cyrus用bash 4.1+ ...
  • 你可以用一个bool变量来做这个,比如boolean newLine = false; ,初始化为false 。 这将是一个指示器,让你知道最后一个角色是A. boolean newLine = false; FILE *fp; int c; fp = fopen("datafile.txt", "w"); while((c = fgetc(fp)) != EOF) { if (newLine) { // Here you put ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。