1

char添加参数的正确方法charQueuefinal ConcurrentLinkedQueue<Character>什么?

甲骨文似乎说它应该工作:

从 char 类型到 Character 类型

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7

代码:

package telnet;

import static java.lang.System.out;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;

public class InputStreamWorker {

    private final static Logger LOG = Logger.getLogger(InputStreamWorker.class.getName());

    public InputStreamWorker() {
    }

    public void print(final InputStream inputStream,  final ConcurrentLinkedQueue<Character> charQueue) {

        Thread print = new Thread() {

            StringBuilder sb = new StringBuilder();

            @Override
            public void run() {
                try {
                    char ch = (char) inputStream.read();
                    sb.append(ch);
                    while (255 > ch && ch >= 0) {
                        charQueue.add(ch);
                        ch = (char) inputStream.read();
                        System.out.print(ch);
                    }
                } catch (IOException ex) {
                    out.println("cannot read inputStream:\t" + ex);
                }
            }
        };
        print.start();
    }
}

从构建结果中提取:

-do-compile:
    [mkdir] Created dir: /home/thufir/NetBeansProjects/TelnetConsole/build/empty
    [mkdir] Created dir: /home/thufir/NetBeansProjects/TelnetConsole/build/generated-sources/ap-source-output
    [javac] Compiling 11 source files to /home/thufir/NetBeansProjects/TelnetConsole/build/classes
    [javac] /home/thufir/NetBeansProjects/TelnetConsole/src/telnet/InputStreamWorker.java:28: error: no suitable method found for add(char)
    [javac]                         charQueue.add(ch);
    [javac]                                  ^
    [javac]     method ConcurrentLinkedQueue.add(Character) is not applicable
    [javac]       (actual argument char cannot be converted to Character by method invocation conversion)
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
    [javac] 1 error
4

2 回答 2

3

你是对的,它应该可以正常工作,因为方法调用转换允许从char到的装箱转换Character。您的代码在我的机器上编译得很好,所以我怀疑是 NetBean 特定的问题。

同时,您可以显式转换 from chartoCharacter以取悦编译器。这应该可以解决问题:

char ch = Character.valueOf(inputStream.read());
于 2013-09-04T22:51:40.727 回答
2

问题出在我自己的创造上。在同一个包中有一个Character类正在创建,现在很明显,命名冲突。

将类重命名为MyCharacter并检查使用的队列Character是否已修复错误。

于 2013-09-04T23:21:08.490 回答