各种算法数据类型转换处理
字符与字符串
- 字符串转字符数组
Sting s;
Char[] c = s.toCharArray();
- 字符转字符串
char num;
Character.toString(num);
- 其他类型转字符串类型
int b = 10;
String a = String.valueOf(b);
- 判断字符串中是否包含某字符
String.contains();
- 字符串取出连续字符
String s;
String temp = s.substring(i-2,i);
- 字符串比较大小
tmp.compareTO("10") >=0 ? 1 : 0;
StringBuilder用法
StringBuffer是线程安全的,而StringBuilder则没有实现线程安全功能,所以性能略高
StringBuffer sb1 = new StringBuffer("123");
StringBuilder sb2 = new StringBuilder("123");
//字符拼接
sb1.append("456");
sb2.append("456");
//转字符串
sb1.toString();
sb2.toString();
栈的数据操作
创建一个栈
Stack<TreeNode> stack = new Stack();
//判断栈满
stack.isFull();
//判断栈空
stack.isEmpty();
//入栈操作push
stack.push();
//出栈操作pop,将栈顶的数据返回
stack.pop();
//显示栈的情况,需要从栈顶开始显示数据
stack.list();
队列的数据操作
// 创建一个队列
Queue<TreeNode> queue = new LinkedList<>();
//判断队列是否为空
queue.isEmpty();
//判断队列是否已满
queue.isFull();
//向队列尾部添加数据
queue.add(); //容量已满,会抛出IllegalStateException异常
queue.offer(); //容量已满,会返回false
//获取队列首元素并从队列中删除
queue.remove(); //队列元素为空,会抛出NoSuchElementException异常
queue.poll() //队列元素为空,会返回null
//获取队列首元素但并不从队列中删除
queue.element(); //队列元素为空,会抛出NoSuchElementException异常
queue.peek(); //队列元素为空,会返回null
//获取队列的长度
queue.size();
List集合转数组
- 遍历遍历List中的元素添加到int[]数组中
List<Integer> list = new ArrayList<>();
int[] res = new int[list.size()];
int i = 0;
for(Integer num : list) {
res[i++] = num;
}
- 利用Java8的stream()
int[] res = list.stream().mapToInt(Integer::intValue).toArray();
- List<Integer> 使用toArray 转换为Integer数组:
Integer[] integer = list.toArray(new Integer[list.size()]);