前言:不常用,但,很有用的java方法,总结如下
1.String
indexOf(String str, int fromIndex);
/**
* Returns the index within this string of the first occurrence of the
* specified substring, starting at the specified index.
* // 获取指定子字符串的,从指定的下标开始的,第一次出现在字符串中的下标。
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* <i>k</i> >= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index from which to start the search.
* @return the index of the first occurrence of the specified substring,
* starting at the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
2.list
toArray();
// 转对象时,在toArray中添加,指定长度的对象数组
List<Criteria> listCriteria = new ArrayList<>();
listCriteria.add(concatQuery(tenantId, formId, condition1));
listCriteria.toArray(new Criteria[listCriteria.size()])
// 转字符串时,在toArray中添加,指定长度的字符串数组
List<String> stringList = new ArrayList<>();
stringList.toArray(new String[stringList.size()]);
3.BigDecimal
public static void main(String[] args) {
// 各种类型转bigDecimal
double num = 2.12324;
int number = 1234;
String str = "123.4";
float fl = 123.34f;
BigDecimal bigDecimal = new BigDecimal(num);
BigDecimal bigDecimaInt = new BigDecimal(number);
BigDecimal bigDecimaStr = new BigDecimal(str);
BigDecimal bigDecimaFl = new BigDecimal(fl);
// setScale(保留位数,BigDecimal.ROUND_HALF_UP) 四舍五入
BigDecimal bd1 = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
double lastNumber = Double.parseDouble(bd1.toString());
}
4.Pattern
public void test() {
String beMatched = "xx";
String regx = "^\\d+$|-\\d+$";
// 1. String 匹配, 他的底层是2.
boolean resultStr = beMatched.matches(regx);
// 2. Pattern 匹配, 他的底层是3.
boolean resultPattern = Pattern.matches(regx, beMatched);
// 3. 完全匹配:当且仅当,整个区域匹配时,返回true
boolean resultMatch = Pattern.compile(regx).matcher(beMatched).matches();
// 4. 局部匹配:regx 能够匹配beMatched局部,返回true
boolean resultFind = Pattern.compile(regx).matcher(beMatched).find();
}
不要直接使用beMatched.matches(regx)
/**
* 数字类型匹配,直接使用NumberFormat
*/
private static final Pattern NUMBER_PATTERN = Pattern.compile("^\\d+$|-\\d+$");
NumberFormat numberFormat = NumberFormat.getNumberInstance();
if (NUMBER_PATTERN.matcher(value).find()) {
value = numberFormat.format(Long.valueOf(value));
}
commonData.setValue(value);