Home > OS >  How to store null elements in some object array and to know they are stored intentionally(not genera
How to store null elements in some object array and to know they are stored intentionally(not genera

Time:12-11

I am creating ExpandableArray class what contains Product classes inside. I have method add(Product p) that adds Product in first null position in my ExpandableArray. And method replace(index int, Product p) - replaces product with this index by with p.

i have confronted following situation:

ExpandableArray expArr = new ExpandableArray(3); // let initial size be 3 products.
expArr.add(p1);
expArr.add(p2);
expArr.replace(0,null) // [null,p2,null]. 

notice that i replaced first element by null intentionally! method add shouldn't touch it, it should work with the second null.

But how do i do that?

My solution is to make integer[]intentionedNullIndexes array inside ExpandableArray, and it will contain all indexes will intentioned nulls. so method add firstly will check if this null index is in intentionedNullIndexes and if it is he won't touch it.

i don't like this solution because it's hard to implement and wastes MANY RAM. Any suggestions?

CodePudding user response:

Your requirement is an XY-problem.

It's an antipattern when null has some kind of special meaning in your business logic. The only valid meaning of null - is no data (otherwise the code becomes muddy).

i don't like this solution because it's hard to implement and wastes MANY RAM

There's no need to waste lots of memory. You need only one reference to a placeholder object, which you can use as many times as you need.

  • Related