1 52 53 package freemarker.template.utility; 54 55 import java.math.BigDecimal ; 56 import java.math.BigInteger ; 57 import java.util.ArrayList ; 58 import java.util.Collections ; 59 import java.util.List ; 60 61 65 public class OptimizerUtil 66 { 67 private static final BigInteger INTEGER_MIN = new BigInteger (Integer.toString(Integer.MIN_VALUE)); 68 private static final BigInteger INTEGER_MAX = new BigInteger (Integer.toString(Integer.MAX_VALUE)); 69 private static final BigInteger LONG_MIN = new BigInteger (Long.toString(Long.MIN_VALUE)); 70 private static final BigInteger LONG_MAX = new BigInteger (Long.toString(Long.MAX_VALUE)); 71 72 private OptimizerUtil() 73 { 74 } 75 76 public static List optimizeListStorage(List list) 77 { 78 switch(list.size()) 79 { 80 case 0: 81 { 82 return Collections.EMPTY_LIST; 83 } 84 case 1: 85 { 86 return Collections12.singletonList(list.get(0)); 87 } 88 default: 89 { 90 if(list instanceof ArrayList ) 91 { 92 ((ArrayList )list).trimToSize(); 93 } 94 return list; 95 } 96 } 97 } 98 99 109 public static Number optimizeNumberRepresentation(Number number) 110 { 111 if(number instanceof BigDecimal ) 112 { 113 BigDecimal bd = (BigDecimal ) number; 114 if(bd.scale() == 0) 115 { 116 number = bd.unscaledValue(); 118 } 119 else 120 { 121 double d = bd.doubleValue(); 122 if(d != Double.POSITIVE_INFINITY && d != Double.NEGATIVE_INFINITY) 123 { 124 return new Double (d); 126 } 127 } 128 } 129 if(number instanceof BigInteger ) 130 { 131 BigInteger bi = (BigInteger )number; 132 if(bi.compareTo(INTEGER_MAX) <= 0 && bi.compareTo(INTEGER_MIN) >= 0) 133 { 134 return new Integer (bi.intValue()); 136 } 137 if(bi.compareTo(LONG_MAX) <= 0 && bi.compareTo(LONG_MIN) >= 0) 138 { 139 return new Long (bi.longValue()); 141 } 142 } 143 return number; 144 } 145 } 146 | Popular Tags |