代码之家  ›  专栏  ›  技术社区  ›  Ashish Agarwal

为什么JavaSiges()小于0?

  •  42
  • Ashish Agarwal  · 技术社区  · 16 年前

    为什么是 list.size()>0 比慢 list.isEmpty() 在Java中?换句话说为什么 isEmpty() 优于 size()>0 ?

    当我在 ArrayList ,则速度应相同:

    数组列表大小()

        /**
         * Returns the number of elements in this list.
         *
         * @return the number of elements in this list
         */
        public int size() {
          return size;
        }
    

    数组列表.isEmpty())

        /**
         * Returns <tt>true</tt> if this list contains no elements.
         *
         * @return <tt>true</tt> if this list contains no elements
         */
        public boolean isEmpty() {
            return size == 0;
         }
    

    如果我们只是编写一个简单的程序来获取这两种方法所花费的时间,这种情况下 size() 将采取更多 iSimple() 在所有情况下,为什么会这样?

    这是我的测试代码;

    import java.util.List;
    import java.util.Vector;
    
    public class Main {
        public static void main(String[] args) {
            List l=new Vector();
            int i=0;
            for(i=0;i<10000;i++){
                l.add(new Integer(i).toString());
            }
            System.out.println(i);
            Long sTime=System.nanoTime();
            l.size();
            Long eTime=System.nanoTime();
            l.isEmpty();
            Long eeTime=System.nanoTime();
            System.out.println(eTime-sTime);
            System.out.println(eeTime-eTime);
        }
    }
    

    在这里 eTime-sTime>eeTime-eTime 在所有情况下。为什么?

    9 回复  |  直到 12 年前
        1
  •  53
  •   JRL    16 年前

        2
  •  75
  •   Andrzej Doyle    16 年前

    ArrayList

    1. size() == 0 isEmpty()
    2. isEmpty

    LinkedList

        4
  •  5
  •   wds    16 年前

    eTime-sTime>eeTime-eTime

    l.size() == 0

    size() isEmpty() Vector ArrayList

    Long long

        5
  •  4
  •   sicotron    12 年前

        6
  •  2
  •   Joachim Sauer    16 年前

    isEmpty() size()

    size()==0

        7
  •  1
  •   Stephen Denne    16 年前

        9
  •  0
  •   Jesper    16 年前

    List

    ArrayList isEmpty size

    public boolean isEmpty() {
        return size == 0;
    }
    
    public int size() {
        return size;
    }
    

    isEmpty() size() == 0

    推荐文章