Java 数组的 12 个最佳方法
2024-10-12 19:28:48
1. 声明一个数组
String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};
2. 输出一个数组
int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray); // print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d System.out.println(intArrayString);
// [1, 2, 3, 4, 5]
3. 从一个数组创建数组列表
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(arrayList);
// [a, b, c, d, e]
4. 检查一个数组是否包含某个值
String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true
5. 连接两个数组
int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
6. 声明一个内联数组(Array inline)
method(new String[]{"a", "b", "c", "d", "e"});
7. 把提供的数组元素放入一个字符串
// containing the provided list of elements
// Apache common lang
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
System.out.println(j);
// a, b, c
8. 将一个数组列表转换为数组
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
for (String s : stringArr)
System.out.println(s);
9. 将一个数组转换为集(set)
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set);
//[d, e, b, c, a]
10. 逆向一个数组
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]
11. 移除数组中的元素
int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));
12. 将整数转换为字节数组
byte[] bytes = ByteBuffer.allocate(4).putInt(8).array(); for (byte t : bytes) {
System.out.format("0x%x ", t);
}
最新文章
- [LeetCode] Gas Station 加油站问题
- hdu3294 girl‘s research
- InnoDB is limited to row-logging when transaction isolation level is READ COMMIT
- 信息加密之信息摘要加密MD2、MD4、MD5
- 记一次动态调用WebService
- MYSQL procedure
- 如何精通java技术
- Servlet的init()方法如何才会在服务器启动时执行
- Uva 10780 Again Prime? No Time.(分解质因子)
- [转]使用sklearn进行集成学习——实践
- 用一条SQL语句查出每门课都大于80分的学生的姓名
- jQuery Mobile Slider 禁用点击事件
- 关于Mysql5.7高版本group by新特性报错
- scala学习笔记2(类,继承,抽象类)
- mysql 事物没提交导致事物一直运行解决方案
- cout关闭输出缓冲,调试用
- synchronized的一些记录
- SQL GROUP BY对多个字段进行分组
- 使用k8s &;&; minio 进行 postgres 数据库自动备份
- eclipse创建maven组合项目
热门文章
- centos7执行 wget命令: command not found的两种解决方法
- MySQL保存或更新 saveOrUpdate
- mysql索引 B+tree
- (五)消费Dubbo服务
- 解决Too many connections问题
- OpenStack中的Multipath faulty device的成因及解决(part 1)
- 最小二乘法 及python 实现
- Educational Codeforces Round 41 (Rated for Div. 2)
- CSS------当内容超出div宽度后自动换行和限制文字不超出div宽度和高度
- [C] 错误笔记:函数调用——值传递