-1

java doc for java.util.List#size()

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Research java.util.LinkedList source code:

public method:

public boolean add(E e) {
    addBefore(e, header);
        return true;
    }

private Entry<E> addBefore(E e, Entry<E> entry) {
    Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
    newEntry.previous.next = newEntry;
    newEntry.next.previous = newEntry;
    size++;
    modCount++;
    return newEntry;
 }

Thus if before adding element size equals Integer.MAX_VALUE size will become -Integer.MAX_VALUE-1

method size just returns field value without checks:

 public int size() {
    return size;
 }

What do you think about it?

sakura
  • 2,249
  • 2
  • 26
  • 39
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

-1

You will run out of memory long before you've managed to put over 2 billion objects inside the list, so there's nothing to worry about.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Even then, you wouldn't keep a List that large in memory. It wouldn't be effective. But I promise that when you have a few terabytes of memory in your computer, that Java version will have upgraded the size() method to return a long :) – Kayaman Apr 08 '14 at 10:46
  • 1
    It is question about contract. not about effective. – gstackoverflow Apr 08 '14 at 10:47
  • Well, obviously it doesn't fulfill the contract. My opinion is that this is highly irrelevant for any fruitful programming. It will take years before that would be an issue. – Kayaman Apr 08 '14 at 10:50
  • looks like different versions of evolutions for LinkedList and List. I think that good solving - write in List java doc that it works only while size – gstackoverflow Apr 08 '14 at 10:55
  • I would imagine there are more important things to worry about in the JDK than this. – Kayaman Apr 08 '14 at 10:59
  • It is hidden future problem – gstackoverflow Apr 08 '14 at 11:00
  • No it's not. You're talking about lists with over 2 billion elements. If those become commonplace, we won't be writing Java anymore by then. – Kayaman Apr 08 '14 at 11:59
  • Don't you think that memory in future will so fast ? – gstackoverflow Apr 08 '14 at 12:41
  • You're assuming that memory size and speed will increase (which is true), but you're also assuming that everything else remains the same (which is false). – Kayaman Apr 08 '14 at 13:09