常用工具类 1 错误处理: 1.1 自定义异常 public class CustomException extends Exception{ public CustomException(){ //无参,有时会用到 } public CustomException(String message){ super(message); } } 1.2 捕获异常转换成另外一种异常抛出 package com.lxj; import com.lxj.Test; public class HelloWorld { private int cc = 99; public static void main(String[] args){ try{ HelloWorld h = new HelloWorld(); h.test2(); }catch(Exception e){ e.printStackTrace(); }finally{ System.out.println("结束了") } } public void test1() throws Exception{ throw new Exception("牛逼"); } public void test2() throws Exception{ try{ this.test1(); }catch(Exception e){ //RuntimeException r = new RuntimeException(e); //不转换异常类型,不改变里面的异常提示 RuntimeException r = new RuntimeException("runtime 异常"); //转换异常类型,改变里面异常信息 r.initCause(e); throw r; } } } 2 java中的字符串 2.1 比较字符串值是否相等要用equals,==比较的是内存地址 2.2 java中String new和直接赋值的区别: new,会在java的堆内存中创建对象, 有几个new就有几个对象。直接赋值, 是从字符串常量池中取值。 例如 String str1 = "a"; String str2 = "a"; System.out.println(str1==str2);结果为true,地址值都是字符串长量池中的"a". String str3 = new String("a");String str4 = new String("a");System.out.println(str3==str4);结果为false. 应为new会在堆中创建两个字符串对象, 地址值不同 2.3 常用方法: int length() : 返回当前字符串长度 int indexOf(int ch) :查找ch字符在该字符串中第一次出现的位置 int indexOf(String str):查找str字符串在该字符串中第一次出现的位置 int lastIndexOf(int ch):查找ch字符在该字符串中最后一次出现的位置 int lastIndexOf(Sting str):查找str字符串在该字符串最后一次出现的位置 String substring(int beginIndex) :获取从beginIndex位置开始到结束的子字符串 【注】:包含beginIndex位置字符 String substring(int beginIndex,int endIndex) :获取从beginIndex位置开始到endIndex位置结束的子字符串 【注】:包含beginIndex位置字符,不包含endIndex位置字符 String trim() :去除字符串前后空格 boolean equals(Object obj) : 将字符串与指定对象比较 String toLowerCase():将字符串全转为小写 String toUpperCase():将字符串全转为大写 char charAt(int index) :获取字符串中指定位置的字符 String[] split(String regex,int limit) :将字符串分割为子字符串,返回字符串数组 byte[] getBytes():将字符串转为byte数组 byte例子: String str = "haha niubi"; byte[] b = str.getBytes(); for(int i=0;i<b.length;i++){ System.out.print(b[i]+" "); } //104 97 104 97 32 110 105 117 98 105 2.3 StringBuffer、StringBuilder(StringBuilder实现了线程安全性能更高): 2.3.1 相对于普通定义字符串,如果定义一个字符串在重新使其改变值,普通定义的字符串会另开辟空间,而这两个类会直接修改元内存地址值,不需要另开辟空间 2.3.2 定义StringBuilder类: StringBuilder str1 = new StringBuilder(); StringBuilder str2 = new StringBuilder("哈哈哈"); System.out.println(str2); //哈哈哈 2.3.3 StringBuilder类常用的方法: StringBuilder append():当前字符串后拼接 StringBuilder insert(位置,内容):将要插入的字符串插入指定位置 String toString():转为字符串 int length() :获取字符串长度 3 java中的包装类 :基本数据类型(byte、short、int、long、float、double、char、blean)不具备对象类型,比如不能调用方法,为了让他们能调用java提供了包装类 【注】:在 JDK1.5 引入自动装箱和拆箱的机制后,包装类和基本类型之间的转换就更加轻松便利了。 以int为例子: 3.1 装箱:把基本类型转换成包装类,使其具有对象的性质,又可分为手动装箱和自动装箱 如:int i =10; Integer x = new Integer(i); //手动装箱 Integer y = i ; //自动装箱 int z = i + x ;// 20 将基本数据类型与对象计算 3.2 拆箱:和装箱相反,把包装类对象转换成基本类型的值,又可分为手动拆箱和自动拆箱 Integer j = new Integer(8);//定义一个Integer包装类对象,值为8 int m = j.intValue();//手动拆箱为int类型 int n = j;//自动拆箱为int类型 4 java中基本数据类型与字符串相互转换: 4.1 基本数据类型转换为字符串: int a = 2; 4.1.1 toString : String str1 = Integer.toString(a); 4.1.2 valueOf: String str1 = String.valueOf(a); 4.1.3 用一个空字符串加上基本数据类型,得到的就是基本类型数据对应的字符串: String str3 = a + ""; 4.2 字符串转换为基本数据类型: String str = "9"; 4.2.1 :调用包装类的parseXxx静态方法 int d = Integer.parseInt(str); 4.2.2 : 调用包装类的valueOf方法转换为基本类型的包装类,会自动拆箱 int e = Integer.ValueOf(str); 5 Date与SimpleDateFormat、Calendar类表示时间: 5.1 Date:java.util.Date ,最主要用来获取当前时间 Date d = new Date(); System.out.println(d); 5.2 SimpleDateFormat:java.text.SimpleDateFormat,用来格式化时间 5.2.1 format:将日期转化为指定文本格式显示 Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String today = sdf.format(d); 5.2.2 parse:将文本转换为日期 String day = "2017年08月11日 11点21分00秒"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); Date date = sdf.parse(day); 5.3 Calendar:java.util.Calendar ,Date设计缺陷,不建议使用Date,建议使用Carlendar代替Date,Carlendar是个抽象类,通过调用内部getInstance获取Calendar对象 Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; //0代表1月 int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); System.out.println(year + "-" +month + "-" +day + " " +hour + ":" +minute + ":" +second); //2017-8-11 11:43:42 6 Math :用来计算的类 6.1 常用方法: long round():四舍五入取整 double floor():去尾法取整 double ceil():进一取整 double random():随机数0~1 例:产生[0,99)(包含0不包含99)之间的随机整数 :(int)(Math.random() * 99) 7 集合(Collection、Map): 7.1 Collection: 7.1.1 : List(序列) :有序的,可以重复的 实现类 7.1.1.1 :ArrayList(数组序列) 7.1.1.2 :LinkedList(链表) 7.1.2 : Queue(队列) :有序的,可以重复的 实现类 7.1.2.1 :LinkedList(链表) 7.1.3 : Set(集):无序的,不可重复的 实现类 7.1.3.1 :Hashset 7.2 Map: 实现类 7.2.1 HashMap 7.3 Collection下的List之ArrayList 7.3.1 add: Course cr1 = new Course("1","数据结构"); //添加到序列 this.coursesToSelect.add(cr1); //从序列中取出 Course temp = (Course) this.coursesToSelect.get(0); //对象存入集合(collection、map)都变成了object类型,取出来时候要类型转换,向下转型 System.out.println(temp.id + "_" +temp.name); //1_数据结构 Course cr2 = new Course("2","C语言"); this.coursesToSelect.add(0,cr2); //在list最开始添加数据 Course temp2 = (Course) this.coursesToSelect.get(0); System.out.println(temp2.id + "_" +temp2.name); //1_数据结构 //如果现在list中有2个元素,这时候只能像第3个元素插入,如果想5、6。。插入,就会数组越界 Course cr3 = new Course("3","N语言"); this.coursesToSelect.add(4,cr3); //list数据添加不允许中间隔开,要紧挨着,这样会报越界 7.3.2 addAll: //addAll 将对象批量添加到list Course[] course = {new Course("4","离散数学"),new Course("5","汇编语言")}; this.coursesToSelect.addAll(Arrays.asList(course)); Course[] course2 = {new Course("5","语文"),new Course("6","数学")}; this.coursesToSelect.addAll(2,Arrays.asList(course)); //"5语文"在list的第2个位置,"6数学"在list第3个位置 7.3.3 site():获取list长度 7.3.4 get():从list中获取单个数据 7.3.4.1 普通遍历for ListTest lt = new ListTest(); lt.testAdd(); //批量添加课程 List courseList = lt.coursesToSelect; for(int i = 0 ;i<courseList.size();i++){ Course course = (Course)courseList.get(i); System.out.println(course.id+" "+course.name); } 7.3.4.2 迭代器iterator: ListTest lt = new ListTest(); lt.testAdd(); Iterator iter = lt.coursesToSelect.iterator(); while(iter.hasNext()){ Course course = (Course)iter.next(); System.out.println(course.id + " "+course.name); } 7.3.4.3 用foreach ListTest lt = new ListTest(); lt.testAdd(); for(Object object :lt.coursesToSelect){ Course course = (Course)object; System.out.println(course.id + " " + course.name); } 7.3.5 set修改list中某个位置的对象 ListTest lt = new ListTest(); List l = lt.coursesToSelect; l.set(3,new Course("8","跑步")) 7.3.6 remove 删除list中单个对象 ListTest lt = new ListTest(); lt.testAdd();//添加了4个课程 Course course = (Course)lt.coursesToSelect.get(2); lt.coursesToSelect.remove(course); //删除一个课程 for(Object obj :lt.coursesToSelect){ Course cou = (Course)obj; System.out.println(cou.id + " "+cou.name); //纸打印3个 } 7.3.7 removeAll 批量删除list中对象 ListTest lt = new ListTest(); lt.testAdd();//添加了4个课程 Course courses[] = {(Course)lt.coursesToSelect.get(0),(Course)lt.coursesToSelect.get(2)}; lt.coursesToSelect.removeAll(Arrays.asList(courses)); //删除两个课程 7.4 泛型 :通过泛型限制向集合中添加的数据类型(比如list是添加课程对象的,加入字符串或者其他对象等都会在编译的时候报错),取出来直接用就行了,再也不需要再取出来去类型转换 7.4.1 定义: public List<Course> courses; //<>即为泛型,此list只能添加course对象,添加其他就报错 7.4.2 取出来不需要转换(以foreach为例): ListTest lt = new ListTest(); lt.testAdd(); for(Course course :lt.coursesToSelect){ System.out.println(course.id + " " + course.name); } 7.4.3 泛型集合(connection、map)中不仅可以存放泛型类型对象,也可以存放泛型类型的子类对象: 如 List<Course> 的List不仅可以存Course的对象,也可以存Course子类对象 7.4.4 泛型不能使用基本数据类型,必须用包装类替换基本数据类型: 【错误】:List<int> list = new ArrayList<int>(); 【正确】:List<Integer> list = new ArrayList<Integer>(); 7.5 set集:无序不可重复 7.5.1 与list一样存在 add()、addAll()、size()、remove()、removeAll()方法 7.5.2 与list不一样的是不存在set()、get()修改元素获取元素,因为set是无序的,无法知道在哪个位置是哪个元素 7.5.3 set只能通过循环或者迭代获取内容,不能通过get获取 7.5.4 set可以添加null,但是一般对业务没有实际用途 7.6 map:key-value 映射关系 put(key,value): remove(key): put、ketSet(返回所有键的集合)、remove、entrySet(返回map中所有键值对的集合)例子: public class MapTest { public Map<String,Student> students; public MapTest(){ this.students = new HashMap<String,Student>(); } /** * map put(添加) */ public void testPut(){ Scanner console = new Scanner(System.in); int i = 0; while(i<3){ System.out.println("请输入学生id:"); String ID = console.next(); Student st = this.students.get(ID); if(st == null){ System.out.println("请输入姓名"); String Name = console.next(); Student newst = new Student(ID,Name); this.students.put(ID, newst); System.out.println("成功添加用户用户:"+Name); i++; }else{ System.out.println("该用户已存在"); continue; } } } /** * map ketSet */ public void testKeySet(){ //通过keyset方法,返回map中所有“键”的set集合 Set<String> ketSet = this.students.keySet(); //便利set获取到每一个“键”,在调用map的get方法传入键值,就可以获取到map中该“键”对应的value System.out.println("总共有:"+this.students.size()+"个学生"); for(String ID : ketSet){ Student student = this.students.get(ID); if(student != null){ System.out.println("学生:"+student.name); } } } /** * map remove */ public void testRemove(){ Scanner console = new Scanner(System.in); while(true){ System.out.println("请输入要删除学生的ID"); String ID = console.next(); Student st = this.students.get(ID); if(st == null){ System.out.println("ID不存在"); continue; }else{ this.students.remove(ID); System.out.println("删除成功:"+ st.name); break; } } } /** * map entrySet */ public void testEntrySet(){ //通过keyset方法,返回map中所有“键”的set集合 Set<Entry<String,Student>> entrySet = this.students.entrySet(); for(Entry<String,Student> entry : entrySet){ System.out.println("取得键:"+entry.getKey()); System.out.println("取得对应的值:"+entry.getValue().name); } } /** * map put(修改) */ public void testModify(){ Scanner console = new Scanner(System.in); while(true){ System.out.println("请输入要修改姓名学生的ID"); String ID = console.next(); Student st = this.students.get(ID); if(st == null){ System.out.println("ID不存在"); continue; } System.out.println("当前学生姓名为:"+ st.name + "请输入新的姓名"); String NEWNAME = console.next(); Student newst = new Student(ID,NEWNAME); this.students.put(ID, newst); System.out.println("修改成功"); break; } } } 主类: public static void main(String[] args){ MapTest mt = new MapTest(); //add mt.testPut(); mt.testKeySet(); //remove // mt.testRemove(); // mt.testEntrySet(); //update mt.testModify(); mt.testEntrySet(); } 7.7 contains、containsAll(与addAll、removeAll用法一样):SET、LIST是否包含某个对象 7.7.1 :LIST中是否包含某个对象 7.7.1.1 :判断对象是否存在SET、LIST /** * 测试List contains方法 */ public void testListContains(){ Course course = this.coursesToSelect.get(0); System.out.println("取得课程:"+course.name); System.out.println("备选课程中是否包含课程::"+course.name+","+this.coursesToSelect.contains(course)); //True } 7.7.1.2 :判断对象中某个属性是否一样从而判断对象是否相等,重写equals方法 ,实际上contains也是一个个去比较equals方法 如:Course中有id、name,默认是id,name都相同才认为相同,但是现在我想只要课程name相同就算存在,那equals重写如下,排除id比较: public class Course { public String id; public String name; public Course(String id,String name){ this.id = id; this.name = name; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Course other = (Course) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } //调用 public class SetTest { public List<Course> coursesToSelect; public SetTest(){ this.coursesToSelect = new ArrayList(); } public void testListContains(){ Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")}; this.coursesToSelect.addAll(Arrays.asList(course)); Course course =new Course("4","离散数学"); System.out.println("备选课程中是否包含课程::"+course.name+","+this.coursesToSelect.contains(course)); //true } } 7.7.2 :SET中是否包含某个对象 7.7.2.1 SET写法与LIST相同,当你输入一个SET中存在的一个name时候,会返回false,由于Set是通过HashSet实例化的,HashSet会执行hashcode方法, SET在调用contains时候,不止回去对比equals,在调用equals对比之前,先去调了hashcode,所以这里不仅用重写equals,也要重写hashcode 重写代码如下: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Course other = (Course) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } //我们只对比name属性,重写了hashcode与equals之后,通过SET在去调用contains对比,如果name存在就不会再返回false了,具体代码参考LIST中,只需要把LIST换成SET 7.7 indexOf:返回对象在LIST中的第一次出现的索引位置,原理跟contains差不多,也是循环比较每个对象中的equals方法,如果为true返回第一次出现的索引位置 list.indexOf(obj) lasatIndexOf: 返回对象在LIST中的最后一次出现的索引位置 list.lasatIndexOf(obj) 【注意】:如果都没找到,返回-1 ,其实用法跟字符串的indexOf、lastIndexOf一样 7.8 map中是否包含key、value: 7.8.1 map.containsKey(key) // 判断key是否存在于map的key中 7.8.2 map.contaimsValue(param) //判断param是否存在于map的value中,contaimsValue与LIST、SET一样,如果param是对象,就会去调用里面的equals对比,所以重写equals 7.9 Comparable、Comparator 7.10.1 Comparable接口:可比较的,实现该接口的类的实例可以比较大小,可以进行自然排序,定义了默认比较规则,其实现类需实现compareTo方法, compareTo返回正数表示大,负数表示小,0表示相等 7.10.2 Comparator接口:比较工具接口,用于定义临时比较规则,而不是默认比较规则,其实现类必须实现compare方法,Comparable与Comparator都是Java集合框架的成员。 【注】:所有java集合包含:Collection接口、Map接口、Collections工具类、Comparable接口、Comparator接口 7.10 sort(Collections下的方法):给LIST排序 7.10.1 给数字、字符串排序: public class CollectionsTest { public void testSort1(){ List<Integer> integerList = new ArrayList<Integer>(); Random random = new Random(); Integer k; for(int i=0;i<10;i++){ do{ k = random.nextInt(100); //生成100以内的随机数 }while(integerList.contains(k)); integerList.add(k); System.out.println("成功添加整数:"+k); } System.out.println("排序前"); for(Integer inte : integerList){ System.out.println("元素:"+inte); } //排序 Collections.sort(integerList); System.out.println("排序后"); for(Integer inte : integerList){ System.out.println("元素:"+inte); } } public static void main(String[] args){ CollectionsTest c =new CollectionsTest(); c.testSort1(); } } 7.10.2 给对象排序:想要使用这个sort排序的对象,它的类必须要实现comparable接口或者comparator接口: 7.10.2.1 :实现comparable public class Student implements Comparable<Student>{ public String id; public String name; public Set<Course> courses; public Student(String id,String name){ this.id = id; this.name = name; this.courses = new HashSet<Course>(); } @Override //必须要实现 public int compareTo(Student o) { // TODO Auto-generated method stub return this.id.compareTo(o.id); //只比较id大小 } } //主类调用 public void testSort1(){ List<Student> strList = new ArrayList<Student>(); Random r = new Random(); Student s1 = new Student(String.valueOf(r.nextInt(1000)),"ming"); Student s2 = new Student(String.valueOf(r.nextInt(1000)),"hong"); Student s3 = new Student(String.valueOf(r.nextInt(1000)),"xiao"); Student s4 = new Student(String.valueOf(r.nextInt(1000)),"ha"); strList.add(s1); strList.add(s2); strList.add(s3); strList.add(s4); System.out.println("排序前"); for(Student inte : strList){ System.out.println(inte.id + " " + inte.name); } //排序 Collections.sort(strList); System.out.println("排序后"); for(Student inte : strList){ System.out.println(inte.id + " " + inte.name); } } 【注】:id是字符串,他不会按照数字比较,他会比较第一位数字 7.10.2.2 :实现comparator Student类: public class Student{ public String id; public String name; public Set<Course> courses; public Student(String id,String name){ this.id = id; this.name = name; this.courses = new HashSet<Course>(); } } Comparator定义临时排序类,根据姓名排序 public class StudentComparator implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub return o1.name.compareTo(o2.name); } } //对比排序 public void testSort1(){ List<Student> strList = new ArrayList<Student>(); Random r = new Random(); Student s1 = new Student(String.valueOf(r.nextInt(1000)),"ming"); Student s2 = new Student(String.valueOf(r.nextInt(1000)),"hong"); Student s3 = new Student(String.valueOf(r.nextInt(1000)),"xiao"); Student s4 = new Student(String.valueOf(r.nextInt(1000)),"ha"); strList.add(s1); strList.add(s2); strList.add(s3); strList.add(s4); System.out.println("排序前"); for(Student inte : strList){ System.out.println(inte.id + " " + inte.name); } Collections.sort(strList,new StudentComparator()); System.out.println("排序后"); for(Student inte : strList){ System.out.println(inte.id + " " + inte.name); } }
3、java常用工具类
最新推荐文章于 2024-01-29 11:37:53 发布