2

I have noticed something weird in Spring data for mongo :

MongoRepository extends CrudRepository and the findAll() returns an Iterable which it's ok with the count() method as it returns a long.

class CrudRepository {

  ...

  Iterable<T> findAll();

  long count();
}

In mongo MongoRepository the findAll() method returs a List :

class MongoRepository extends CrudRepository {

  ...  

  @Override
  List<T> findAll();
}

But a List#size() returns an int and the MongoRepository#count() method stay returning a long.

What happens when the collection exceed Integer.MAX_VALUE !? Could we still call List<T> findAll() ?

bubbles
  • 2,597
  • 1
  • 15
  • 40

2 Answers2

3

From java.util.List#size javadoc:

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

So when collection size exceeds Integer.MAX_VALUE the size method will return Integer.MAX_VALUE.

Could we still call List<T> findAll()?

Yes, but most probably the call will fail with OutOfMemoryError

Denis Zavedeev
  • 7,627
  • 4
  • 32
  • 53
3

I liked your view point :) This question looks similar based on what you're asking to this question.

As it mentioned in Java Language Specification: 15.10.1. Array Creation Expressions:

Each dimension expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.

Since dimension has to be an int, we can stores maximum the size 2,147,483,648 in an array and also considering an ArrayList is nothing else but an Array, we can not store more than INTEGER.MAX_VALUE in an ArrayList. (Different implementations of List could behave differently, of course)

Spring Data JPA allows you to customize query methods. You are always free to create a query method which returns type is Iterable.

@Override
Iterable<T> findAll();