Can a dynamic 2D array implement the Java.Collection.size () method?

Ok, so I am creating a dynamic 2D array in Java that implements the java.util.Collection interface. I made my array implementing it, because I wanted it to have the same functionality as normal Collection. However, I cannot implement the method size()because it returns an integer in the interface, and the 2D matrix can potentially overflow the integer type.

Here is a snippet of my class that I am trying to do:

public abstract class AbstractMatrix<E> implements Collection<E>{
     @Override
     public long size() {
         return columns * rows;
     }
}

Now this will not work, because "The return type is incompatible with Collection<E>.size()", and if I change the type to int, the column rows * may overflow.

I know I can't override a size method like this, but is there any way to make sure the method returns the correct size while still implementing the interface Collection?

Yes, I know that this is impractical and probably will never be a problem, but I was interested to know if there is a good solution for this.

+5
source share
4 answers

Although your implementation is sizeuncertain, the contract for Collection#sizeis defined in javadoc :

Returns the number of items in this collection. If this collection contains more Integer.MAX_VALUE elements, Integer.MAX_VALUE is returned.

So, you can calculate the size as longand return Integer.MAX_VALUEif it is larger than Integer.MAX_VALUE.

, LinkedList#add, , size .

+2

, 8 - , int - , - , ( )...

, Iterable, Collection Integer.MAX_VALUE, Javadoc:

. Integer.MAX_VALUE, Integer.MAX_VALUE.

+2

, , , , , ( ) , (runtime) .

0

, . , , 32- , 4 .

Ask yourself, do you really need to be able to support this many objects? Keep in mind that 4 billion and changing 32-bit integers will take up 16 GB of RAM. Using 64-bit java, an array of 4 billion in length Object, set to all null values, will occupy 32 GB, because references to 64-bit java are 64 bits. This does not even take into account the memory used to actually create many classes, which are likely to be much higher.

-1
source

All Articles