Java常用类
1、字符
Character:装箱 拆箱。Character.isDigit('8');、Character.isLetterOrDigit('4');、Character.isWhitespace('\t');、Character.toUpperCase('a')。
public class test { public static void main(String[] args) throws Exception { char c1 = 'a', c2 = 'b'; Character ch = new Character('c'); //装箱 char ch1 = ch.charValue(); //拆箱 System.out.println("" + c1 + c2 + ch.toString() + ch1); } }
String
创建String s1 = new String("hello my name is shine!"); new String(new char[]{'o','k','!'}); String s2 = "hello";
长度:是s1.length()
方法:chartAt() char c = s1.charAt(0);
toCharArray() char[] cs = sentence.toCharArray();
substring() String s2 = s1.substring(index, count);
split() for(String s: s1.split("[\n+|\t+|' '+|','+]+"))
trim() s1.trim() # 删去首位的空白符
toUpperCase() System.out.print(s1.toUpperCase());
indexOf() ('h')、("shine")、('n', 5)分别返回0、17、9, 从第5个字符开始查找'n'。 lastIndexOf()区别在从后找第一个匹配的返回
contains("substring")、startsWith("...")、endsWith("...")
replaceAll(oldS, newS) replaceFirst(oldS, newS)
public static void main(String[] args) throws Exception { String s1 = "hello"; String s2 = new String(s1), s3 = new String("hello"), s4 = s1, s5 = "hello"; System.out.printf("%b\t%b\t%b\t%b\t%d\t%d\t%d\t%b", s1.equals(s2), s1 == s2, s1 == s3, s1 == s4, s1.hashCode(), s2.hashCode(), s3.hashCode(), s1 == s5); }
输出:true false false true 99162322 99162322 99162322 True
class Student{ String name = "default"; int age = -1; Student(String name, int age){ this.name = name; this.age = age; } Student(Student s){ this.name = s.name; this.age = s.age; } } public class test { public static void main(String[] args) throws Exception { Student s1 = new Student("xu", 20); Student s2 = new Student("xu", 20), s3 = new Student(s1); System.out.printf("%b\t%b\t%d\t%d\t%d\n\n", s1 == s2, s1 == s3, s1.hashCode(), s2.hashCode(), s3.hashCode()); } }
StringBuffe 变长字符串 留有冗余长度的字符数组。继承于String
append("...")
delete(index1, index2) 左闭右开
insert(index, "...")
reverse();
2、java.io.File
创建File f = new File("test.txt")
属性:getCanonicalPath() 类似getAbsolutePath()返回String
length()、lastModified() 返回long
exists()、isFile()、isDirectory() 返回boolean
getParent()、getParentFile() 返回String、File
list()、listFiles()
createNewFile()、mkdir()、mkdirs() 创建文件时所在父目录若不存在就报错、mkdirs若所处父文件夹不存在则创建之。
delete()
数据交互:不同介质间的数据交互以流来实现,输入输出字节流InputStream、OutputStream;
硬盘和JVM内存之间的文件数据流FileInputStream和FileOutputStream,utf-8 -> byte[] -> utf-8
FileInputStream fis =new FileInputStream(new File("...")); byte[] data =new byte[(int) f.length()]; fis.read(data); FileOutputStream fos = new FileOutputStream(new File("....")); // 当文件不存在时会制动mkdir创建 fos.write(data); fis.close(); fos.close();
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { File f = new File("d:/lol.txt"); FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } finally { if (null != fis) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
FileReader和FileWriter, utf-8 -> char[] -> utf-8。
FileReader fis =new FileReader("..."); char[] data =new char[(int) f.length()]; fis.read(data); System.out.println(String.valueOf(data)); FileWriter fos = new FileWriter(new File("...")); # mode=w fos.write(data); fis.close(); fos.close();
编码:String <-> byte[]
new String(bytes, StandardCharsets.UTF_8); str.getBytes(StandardCharsets.UTF_8);
3、数组工具类Arrays
int[] a = new int[] { 16, 45, 9, 27, 2, 36 };
复制:int[]b = Arrays.copyOf(a, length=4)、 Arrays.copyOfRange(a, 0, a.length) 左闭右开。
排序:Arrays.sort(a)
搜索:Arrays.binarySearch(a, 2) 返回下标4, 必须sort后查找。
比较:Arrays.equals(a, b) 逐下标的内容比较。
转String:Arrays.toString(a) 转为[16, 45, 9, 27, 2, 36]
4、Math和Random
Math.sqrt(4.1)、Math.pow(2, 3.1)、Math.abs(-1.2)、Math.min(a, b)、Math.ceil(12.5)、Math.round(12.5)
import java.util.Random;
Random r = new Random(); r.nextInt()、r.nextInt(a)、r.nextFloat()、、、
new Date().getTime()、Thread.sleep(2000) // ms毫秒
5、ArrayList常见用法(实现了接口List) 底层是一个数组,超过容量则扩张为2.5倍!
初始化:List<String> li = new ArrayList<String>(Arrays.asList("hello", "shine", "how", "are", "you"));
增:li.add("here")、li.add(2, "you")、li.addAll(li2)
删:li.remove(2)、li.remove("you")
改:li.set(2, "replace")
位置:li.indexOf("how")、li.contains("how")、li.get(i)
li.size()、li.clear()、li.isEmpty()
排序:li.sort(Comparator.naturalOrder()); Comparator.reverseOrder()
转数组:String[] s1 = li.toArray(new String[]{});
遍历:for(String s: li); for(int i = 0; i < li.size(); i++){String s = li.get(i);}
6、LinkedList 底层是双向循环链表,头节点不存放数据
实现了List接口:以上ArrayList的全部方法。
实现了双向链表结构Deque:
getFirst()、peek() 返回队列头节点。
poll() 删除并返回队列头节点。
offer("...") 尾部入队。
头插尾删,First为头,Last为尾。。。peekFirst()、pollFirst()、offerLast()
头插头删:push("...")、E pop()。
7、hashMap 底层是“哈希表结构”-数组和链表的结合。当某链表数据超过8个时就把链表置成红黑树结构(jdk1.8),
数组的下标是key的hashCode,get/put查找key时 key-hashCode存在node则逐一比较equals。

初始化:Map<String, Object> mp = new HashMap<String, Object>(){ {put("hi", "shine"); put("hello", 2);} };
增改:put(key, value)
获取:get(key) null
删除:remove(key)
containsKey(key)、isEmpty()、clear()、size()
values:Collection<Integer> con = map.values(); for(String x : con)
keySet:Set<String> set = map.keySet(); for(String x : set)
遍历:Set<Entry<String, Object>> set = mp.entrySet();
for(Entry<String, Object> s : set){
8、Collections 集合框架/容器的工具类 类似Arrays是数组的工具类。
List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(new Integer[]{16, 2, 24, 9, 45, 8}));
sort(l1)
shuffle(l1)
reverse(l1)
swap(l1, index1=0, index2=5)
rotate(l1, 2) 向右滚动两个位置

浙公网安备 33010602011771号