Java API一些注意的零碎不定期整理

Arrays.binarySearch()

  1. 二分搜索是建立在有序数组上的,所以搜索前排序,否则得到的结果不可行。
  2. 指定from, to的时候,包括from,不包括to
  3. 如果查找到返回对应的位置,没有查找到返回第一个比他大的位置,值为负数,转换后为(-res -1)
  4. 不管指定区间与否,3都成立。

将集合元素反序

Collections.reverse()

运行时间在线性范围,但是需要开辟额外的空间。

将数组转成字符串,并指定分隔符

API

static String   join(CharSequence delimiter, CharSequence... elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
static String   join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

注意这里只能处理字符串数组,对于其他类型的数组不行
对于其他类型的,还没发现好用的,目前只能用Arrays.toString(),再用正则进一步处理

String[] strs = {"1","2","3","4"};
System.out.println(String.join(",", strs));
//1,2,3,4
int[] nums = {1,2,3,4,6,7,8,9};
System.out.println(Arrays.toString(nums).replaceAll("[\\[\\]]", ""));
//1, 2, 3, 4, 6, 7, 8, 9

replace replaceAll replaceFirst区别

replace没有用到正则表达式
repaceAll和replaceFirst都用到正则表达式
replaceAll是贪心的用法
replaceFirst是懒惰的

猜你喜欢

转载自blog.csdn.net/crystal_zero/article/details/73480077