目录
Collections工具类常用算法
1.binarySearch(List extends Comparable super T>> list, T key) 容器有序
2.sort() 对指定列表按升序排序
3.reverse(List> list) 翻转列表
4.shuffle(List> list) 洗牌
5.swap(List> list, int i, int j) 在指定列表的指定位置交换元素
eg:反转
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
System.out.println(list);
Collections.reverse(list);
System.out.println("反转之后"+list);
eg:洗牌
public class CollectionsDemo01 {
public static void main(String[] args) {
List cards = new ArrayList();
//shuffle 洗牌 模拟斗地主
for(int i=0;i<54;i++){
cards.add(i);
}
//洗牌
Collections.shuffle(cards);
//发牌
List p1 = new ArrayList();
List p2 = new ArrayList();
List p3 = new ArrayList();
List last = new ArrayList();
for(int i=0;i<51;i+=3){
p1.add(cards.get(i));
p2.add(cards.get(i+1));
p3.add(cards.get(i+2));
}
//最后三张为底牌
last.add(cards.get(51));
last.add(cards.get(52));
last.add(cards.get(53));
System.out.println("第一个人:"+p1);
System.out.println("第二个人:"+p2);
System.out.println("第三个人:"+p3);
System.out.println("底牌为:"+last);
}
}
运行结果:
第一个人:[45, 2, 18, 33, 49, 14, 15, 46, 41, 20, 50, 42, 26, 29, 44, 12, 9]
第二个人:[19, 40, 25, 32, 34, 24, 4, 11, 3, 47, 37, 10, 51, 0, 23, 16, 27]
第三个人:[22, 36, 7, 5, 1, 38, 13, 30, 17, 21, 39, 31, 53, 48, 6, 43, 28]
底牌为:[35, 52, 8]
处理流
处理流:增强功能、提供性能,节点流之上
一、缓冲流
字节緩冲流
BufferedInputStream
BufferedOutputStream
字符缓冲流
BufferedReader readLine()
BufferedWriter newLine()
二、转换流:字节流转为字符流处理乱码(编码集、解码集)
编码与解码概念
编码:字符 ——编码字符集—> 二进制
解码:二进制 —解码字符集—> 字符
造成乱码的原因:
1.编码与解码的字符集不统一
2.字节缺少,长度缺失
文件乱码
eg:原因1
public static void test1() throws UnsupportedEncodingException{
//解码byte ——> char
String str = "中国";//gbk
//编码char ——> byte
byte[] data = str.getBytes();
//编码与解码字符集统一
System.out.println(new String(data));
data = str.getBytes("utf-8");//设定编码字符集
//不统一出现乱码
System.out.println(new String(data));
//编码
byte[] data2 = "中国".getBytes("utf-8");
//解码
str = new String(data2, "utf-8");
System.out.println(str);
}
编码与解码字符集必须相同,否则乱码
eg:原因2
public static void test2(){
String str = "中国";
byte[] data = str.getBytes();
//字节数不完整
System.out.println(new String(data,0,3));
}
综合:读取、指定编码字符集、写出
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 转换流:字节转为字符
* 1.输出流 OutputStreamWriter编码
* 2.输入流 InputStreamReader解码
*/
public class ConverDemo02 {
public static void main(String[] args) throws IOException{
//指定字符集
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("D:/WorkSpace/demo15/src/demo0719/io/convert/ConverDemo01.java")),"GBK"
)
);
String info = null;
//写出文件
BufferedWriter bw = new BufferedWriter(
new FileWriter("D:/WorkSpace/demo15/src/demo0719/io/convert/encode.txt")
);
while(null!=(info=br.readLine())){
bw.write(info+"\n");
}
bw.flush();
bw.close();
//输出内容
while(null!=(info=br.readLine())){
System.out.println(info);
}
br.close();
}
}
关系图