Missing value in Java

后端 未结 11 2747
慢半拍i
慢半拍i 2021-02-20 11:51

What is the statement that can be used in Java to represent a missing value of a variable. for instance I want to write a code:

if (a>=23)
 income = pay_rate;         


        
11条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-20 12:07

    You can do it following way:

    public abstract class Nullable extends Number {
    
        protected final boolean isNA;
    
    
        protected Nullable(boolean isNA) {
            this.isNA = isNA;
        }
    
        public boolean isNA() {
            return isNA;
        }
    }
    
    
    public final class NullableInt extends Nullable {
    
        public static final NullableInt NA = new NullableInt(0, true);
    
        private final int value;
    
        public NullableInt(int value, boolean isNA) {
            super(isNA);
            this.value = value;
        }
    
        public static NullableInt of(int value) {
            return new NullableInt(value, false);
        }
    
        public int getValue() {
            if (!isNA) {
                return value;
            }
            throw new RuntimeException("Value is NA");
        }
    
        @Override
        public int intValue() {
            return getValue();
        }
    
        @Override
        public long longValue() {
            return getValue();
        }
    
        @Override
        public float floatValue() {
            return getValue();
        }
    
        @Override
        public double doubleValue() {
            return getValue();
        }
    }
    
    public class Test {
    
        public static void main(String[] args) {
            NullableInt[] nullableInts = new NullableInt[3];
            nullableInts[0] = NullableInt.of(1);
            nullableInts[1] = NullableInt.of(2);
            nullableInts[2] = NullableInt.NA;
    
            System.out.println(Arrays.toString(nullableInts));
        }
    }
    

提交回复
热议问题