public final char readChar() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (char)((ch1 << 8) + (ch2 << 0));
    }这是DataInputStream的readChar()源码,请高手解释一下后三句的作用,我知道"|"是或运算,也知道"<<"是左移位,我不是要解释语句的意思,我要知道为什么要这样做才实现readChar()的功能.

解决方案 »

  1.   

    /**
         * Reads the next byte of data from the input stream. The value byte is
         * returned as an <code>int</code> in the range <code>0</code> to
         * <code>255</code>. If no byte is available because the end of the stream
         * has been reached, the value <code>-1</code> is returned. This method
         * blocks until input data is available, the end of the stream is detected,
         * or an exception is thrown.
         *
         * <p> A subclass must provide an implementation of this method.
         *
         * @return     the next byte of data, or <code>-1</code> if the end of the
         *             stream is reached.
         * @exception  IOException  if an I/O error occurs.
         */
        public abstract int read() throws IOException;
    可以看出in.read()读出一个byte。而一个char是由两个byte组成,所以c1保存高位的字节,c2保存地位字节, (char)((ch1 << 8) + (ch2 << 0));是将c1,c2组合到一起成为一个char
      

  2.   

    疑问1 为何要 if ((ch1 | ch2) < 0)2  既然是高位保存在c2,为什么要(ch2 << 0)ch2左移0位有什么意义?不如不移好了。
      

  3.   

    刚才看了一下,确实加了<<0以后多了两条指令,所以不加确实要快
    至于 | 问题,用 |的只用了三条指令
    iload_2
    iload_3
    ior, 而如果这样实现的话 if ((ch1==-1 || ch2==-1))指令就多了
    iload_2
    iconst_m1
    if_icmpeq 20
    iload_3
    iconst_m1
    if_icmpne 28
      

  4.   

    if ((ch1 | ch2) < 0) 要比 if(ch1 <0 || ch2 <0)要快  :)