《工具类及常用算法.ppt》由会员分享,可在线阅读,更多相关《工具类及常用算法.ppt(58页珍藏版)》请在三一办公上搜索。
1、Java程序设计,第7章 工具类及常用算法,Java基础类库,JDK中提供的基础类库又称为JFC(java Foundation Class Library),其中包含很多包,每个包中都有若干特定功能和相互关系的类和接口。一些经常使用的包为:java.lang包/默认加载的包java.io包java.util包java.awt包java.applet包包,Java语言基础类,java.lang这个包包含了运行程序不可少的类,包括基本数据类,基本数学类,字符串处理,异常处理等等。该包在程序时自动引入。java.io标准的输入输出类库,包含程序与系统,用户以及其他程序做的数据交换使用的类,包括基本
2、I/O,文件I/O等。完成与操作系统有关的I/O操作需要用到该包。,Java语言基础类,java.util包括一些实用工具,如Date类,Vector类,Stack类等。使用它们可以方便编程。java.awt图形用户界面(GUI)类库。包括许多界面和资源,如Graphics类,Container类等等。可以利用该包编写标准化的应用程序界面。java.applet用来实现运行于浏览器中的Java Applet的工具类库,常用的类是。,Java语言基础类,其他包还有一些其他的包,如java.rmi是实现远过程调用功能,可以在远程机器上创建对象,在本地机器上使用;java.sql包是实现JDBC的类
3、库。利用这个包可以是程序访问不同类型的数据库。只要安装了对应的驱动程序,同一个程序就可以访问不同的数据库。如果想要详细了解这些系统的类库,可以参考JDK的文档。,Java语言基础类,Object类Object类是所有类的直接或间接父类,也是类库当中所有类的父类,可以和任意类型的对象匹配。所以可以用它作为形参的类型,那么不论何种类型的实际参数都可以与这个形参匹配,从而扩大了方法得适用范围。常用得方法:protected Object clone();/生成当前对象得备份public boolean equals(Object obj);/比较两个对象public String toString(
4、);/返回当前对象得相关信息,Java语言基础类,equals方法该方法用来比较两个对象是否相同,相同返回true,否则返回false。如果一个类没有覆盖equals方法,那么这时候的相等是指两个引用相等,也就是说他们引用的是同一个对象。,Java语言基础类,equals方法运算符关系运算符生成的是一个“布尔”结果。它评价的是运算对象值之间的关系。运算符适用于所有对象,但它的含义通常会使人找不到北。(见例子)一般人都会认为输出结果肯定先是true,再是false,因为两个Integer对象都是相同的。但尽管对象的内容相同,句柄却是不同的,而=比较的正好就是对象句柄。所以输出结果实际上先是fal
5、se,再是true。,Java语言基础类,equals方法若想对比两个对象的实际内容是否相同,又该如何操作呢?此时,必须使用所有对象都适用的特殊方法equals()。(例子)正如我们预计的那样,此时得到的结果是true。但事情并未到此结束!假设您创建了自己的类,就象下面这样(举例)此时的结果又变回了false!这是由于equals()的默认行为是比较句柄。所以除非在自己的新类中改变了equals(),否则不可能表现出我们希望的行为。大多数Java类库都实现了equals(),所以它实际比较的是对象的内容,而非它们的句柄。,Java语言基础类,equals方法总结的来讲,也就是说:equals(
6、)默认的是比较句柄,因为JDK中的许多类在实现的时候都覆盖了equals()方法,所以一般使用java类库中的equals时,比较的是对象的内容;但是,如果用户自己定义一个类,又没有改写equals()方法,那么它比较的是句柄,除非用户自己写equals()方法来使得它的功能为比较对象的内容。,Java语言基础类,toString()toString()方法用来返回对象的字符串表示,可以用来显示一个对象。System.out.println()方法如果带的参数是一个对象的话,那么它会自动调用对象的toString()方法,那么它显示的将是“类名内存地址”。在自定的类中一般来讲覆盖toStrin
7、g()方法。(举例 2个),Java语言基础类,基本数据类型包装类java中提供了基本数据类型的包装类,以于面向对象的思想一致。对应的也有8种:Character,Byte,Short,Integer,Long,Float,Double,Boolean。他们都是作为类来使用。1、提供一些常数方便使用,Integer.MAX_VALUE,Double.NaN等。2、提供valueOf(String),toString()3、通过xxxValue()得到所包装的值4、对toString(),equals()等方法进行覆盖(举例),例7-4,class DoubleString public sta
8、tic void main(String args)double d;String s;/double转换成String的几种方法d=3.1415926;s=+d;s=Double.toString(d);s=new Double(d).toString();s=String.valueOf(d);/string转换成double的几种方法s=3.1414926;tryd=Double.parseDouble(s);d=new Double(s).doubleValue();d=Double.valueOf(s).doubleValue();catch(NumberFormatExceptio
9、n e)e.printStackTrace();,补充:装包与拆包,JDK1.5之前,基本数据类型和包装类不能对等使用。Integer i=new Integer(3);装包int iv=i.intValue();拆包JDK1.5之后,可以自动的进行装包和拆包:自动装包是指基本类型自动转化为包装类型,自动拆包指包装类自动转化为基本类型。Integer i=3;int iv=I;,Java语言基础类,Math类该类提供了一些不同标准的数学函数的方法,这些都是static方法,所以使用的时候不用创建Math类的对象,可以直接通过类名来调用这些方法:Math.所要用的方法。方便编程。关于具体的方法和
10、属性,可以查询JDK的帮助文档。(举例),例7-5,class TestMath public static void main(String args)int a=3;double b=1.5,c=32.2;double f=0.0;f=1.0/2*(a+Math.sqrt(b*Math.sin(c);System.out.println(f=+f);System.out.println(Math.ceil(3.1415)=+Math.ceil(3.1415);System.out.println(Math.floor(3.1415)=+Math.floor(3.1415);System.o
11、ut.println(Math.round(987.654)=+Math.round(987.654);System.out.println(Math.max(-987.654,301)=+Math.max(-987.654,301);System.out.println(Math.PI=+Math.PI);,Java语言基础类,System类该类是一个非常有用的特殊类,提供了标准输入/输出、运行时系统信息等工具。由于该类的一些属性和方法这些都是static的,所以使用的时候不能创建System类的对象,可以直接通过类名来调用这些方法:System.所要用的方法。,Java语言基础类,用sys
12、tem类获得标准输入输出public static InputStream in;public static PrintStream out;public static PrintStream err;使用这些可以从标准输入读入数据或向标准输出输出数据。用system类的方法获得系统信息system类提供一些与运行时系统交互的方法,可以利用它们获得解释器或系统的信息,也可以向运行系统发出指令。public static long current TimeMillis();public static void exit(int status);,示例7-6,主要用来测试System类的基本属性及
13、功能*/import java.util.*;class TestSystem public static void main(String args)Properties a;Enumeration ps;Iterator pi;a=System.getProperties();a.setProperty(test_path,2);/System.setProperties(a);System.out.println(System.getProperty(test_path);System.out.println(System.getProperty(java.version);/*pi=a
14、.entrySet().iterator();while(pi.hasNext()System.out.println(pi.next();*/ps=a.propertyNames();while(ps.hasMoreElements()Object obj=ps.nextElement();Object objVal=a.get(obj);System.out.println(+obj+=+objVal);,字符数组与字符串,字符串是字符的序列,它是组织字符的基本数据结构,从某种程度上来说有些类似于字符的数组。char country=C,h,i,n,a;C+?,在Java中,字符串被当作对
15、象来处理。程序中需要用到的字符串可以分为两大类,一类是创建之后不会再做修改和变动的String类;另一类是创建之后允许再做更改和变化的StringBuffer类。,Java会自动为字符串常量生成一个String类的对象,所以可以直接初始化String对象,如:String s=“SCEMI XMJ!”,用一个已创建的字符串创建另一个字符串,如:String s1=new String(s);,创建字符串对象,使用String类的构造方法创建字符串对象,如:String s=new String(“We are Chinese);,String(char a):用一个字符数组a 创建一个字符串对
16、象,如:char a=X,M,J;String s=new String(a);,String(char a,int startIndex,int count):提取字符数组a 中的一部分字符创建一个字符串对象,如:char a=S,C,E,M,I,X,M,J;String s=new String(a,5,3);,String类常用方法,public int length()获取字符串的长度,public boolean equals(String s)比较当前字符串对象的实体是否与参数指定的字符串s的实体相同,public boolean startsWith(String s)publi
17、c boolean endsWith(String s)判断当前字符串对象的前缀后缀是否是参数指定的字符串s,public int compareTo(String s)比较大小 等 0;大 正;小 负,String s1=new String(“中国.四川”);String s2=new String(“中国.四川”);String s3=new String(“中国”);String s4=new String(“四川”);System.out.println(s1.length();/?System.out.println(s3.length();/?System.out.println
18、(s1=s2);/?System.out.println(s1.equals(s2);/?System.out.println(s1=s2);/?System.out.println(s1=s2);/?System.out.println(s1.equals(s2);/?System.out.println(s1.startsWith(s3);/?System.out.println(s1.endsWith(s4);/?System.out.println(pareTo(s2);/?System.out.println(pareTo(s4);/?,52falsetrue中国.四川truetru
19、etruetrue0-2222,JAVA程序设计,2006.02 By SCEMI XMJ,String类常用方法,public int indexOf(String s,int startpoint)public int lastIndexOf(String s)返回首次出现s的位置。没有-1。,public String substring(int startpoint,int end)从start处截取到尾部end处所得到的字符串。,public String trim()去掉前后空格,public String replaceAll(String old,String new)用参数n
20、ew指定的字符串替换由old指定的所有字符串,public char charAt(int index)返回第index个字符,String s1=new String(“中国.四川.攀枝花”);String s2=new String(“We are like Java”);System.out.println(s1.indexOf(“china”);/对?System.out.println(s2.indexOf(a);/对?System.out.println(s2.indexOf(“a”);/?System.out.println(s2.lastIndexOf(“a”);/?Syste
21、m.out.println(s2.indexOf(“a”,6);/?System.out.println(s2.indexOf(“Java”);/?System.out.println(s1.charAt(6);/?System.out.println(s2.charAt(12);/?System.out.println(s1.substring(3);/?System.out.println(s1.substring(3,5);/?System.out.println(s1.replaceAll(.,);/对?System.out.println(s1.replaceAll(“.”,“#”)
22、;/?System.out.println(s2.replaceAll(“a”,“b”);/?,-1 33151312攀J 四川.攀枝花 四川 语法错#We bre like Jbvb,字符串与基本数据的相互转换,将基本类型数据转换为String型:String.valueOf(基本数据类型)例:String.valueOf(0.34)“0.34”,将String型转换为基本类型数据:03-18提及 Integer.parseInt(String s)Double.parseDouble(String s)例:Double.parseDouble(“12.34”)12.34,JAVA程序设计,
23、StringBuffer类,创建StringBuffe对象StringBuffer()StringBuffer(int size)StringBuffer(String s),length()字符个数,StringBuffer sb=new StringBuffer()sb.length()/0,StringBuffer sb=new StringBuffer(32)sb.length()/0 sb.capacity()/32,StringBuffer sb=new StringBuffer(“SCEMI XMJa”)sb.length()/9 sb.capacity()/25=9+16,St
24、ringBuffer类常用方法,void setCharAt(int n,char ch)用字符ch替换第n个字符,StringBuffer insert(int index,String str)将字符串str插入从index起的当前字符串中,append 数据转化后追加,public StringBuffer reverse()字符翻转,StringBuffer delete(int startpos,int endpos)删除startpos到endpos-1子串,StringBuffer replace(int n,int m,String str)用串str替换当前串从n到m-1的子
25、串,StringBuffer str=new StringBuffer(“123”)str.append(456);/对吗?str=str+“789”/对吗?str.append(“789”);/str?System.out.println(str.setCharAt(0,a);/错 void str.setCharAt(0,a);/str?System.out.println(str);/?str.insert(1,“*”);/str?str.delete(1,4);/str?str.reverse();/str?str.replcae(0,2,“#”);/对吗?str.replcae(5,
26、7,“#”);/str?str.length()/?str.capacity()/?,对 str=“123456”错str=“12346789”str=“a2346789”str=“a*23456789”str=“a23456789”str=“98765432a”对 str=“#765432a”str=“#76#32a”1019,2006.02 By SCEMI XMJ,StringTokenizer类,分解字符串成可被独立使用的单词 java.util包,创建StringTokenizer对象 StringTokenizer(String s)StringTokenizer(String s
27、,String delim),StringTokenizer类常用方法 countTokens()单词计数变量hasMoreTokens()countTokens0 truenextToken()逐个获取单词,import java.util.*;public class ST public static void main(String args)String str=“中国.四川.攀枝花”;StringTokenizer st=new StringTokenizer(str,“.”);int number=st.countTokens();System.out.println(“共有单词:
28、”+number);while(st.hasMoreTokens()System.out.print(number-st.countTokens()+“:”);System.out.println(st.nextToken();,共有单词:3 0:中国 1:四川 2:攀枝花,字符串数组,字符串数组:可以表示一组字符串,public class StrArray public static void main(String args)for(int i=0;iargs.length;i+)System.out.println(argsi);,javac StrArray.javajava Str
29、Array 1st 2nd 3rd,集合类,狭义来讲,集合实际上是用一个数组代表一组对象,在集合中的每一个对象称为一个元素。在集合中的各个元素的具体类型可以不同,一般说来,它们都是由相同的类派生出来的,换言之,它们将其当作Object类型处理(Object类型是Java中所有类的“根”类)。在集合中检索出各个元素以后,一般来讲需要根据具体类型的不同而进行相应的类型转换。,Collection API中的接口和类主要位于java.util包中,其中最主要的接口是Collection,它将一组对象以集合元素的形式组织到一起,然后在其子接口中分别实现不同的组织方式。它的子接口有:Set:不记录元素的
30、保存顺序,且不允许有重复的元素。List:记录元素的保存顺序,且允许有重复的元素。其中,实现Set接口的比较重要的类是HashSet;实现List接口的重要的类有ArrayList,Vector,LinkedList。,Collection API 层次结构,集合类,Collection的方法Public boolean add(Object o);Public boolean remove(Object o);Public void clear();Public boolean contains(Object o);Public int size();Public boolean isEmp
31、ty();Public Iterator iterator();,集合类,Set接口以及HashSet类Set接口是Collection的子接口,拥有与Collection完全相同的接口,它没有什么额外的功能。完全就是一个Collection,只是具有不同的行为而HashSet是实现Set接口的一个类。Set记录的是不重复元素的集合。它里面也可以包含null对象,但一样不可以重复。,集合类,List接口及ArrayList,Vector类List接口也是Collection的子类,它表示对象可重复的集合。对于实现List接口的比较重要的类有:ArrayList,Vector,LinkedLis
32、t。ArrayList、Vector可以说是java中的“动态数组”。数组在用new创建后,其大小是不能改变的,而ArrayList和Vector中的元素的个数是可变的,可以随时添加和删除。,Iterator接口,Iterator接口定义了对Collection类型对象中所含元素的遍历等增强处理功能可以通过Collection接口中定义的iterator()方法获得一个对应的Iterator(实现类)对象Set(实现类)对象对应的Iterator仍然是无序的List(实现类)对象对应的ListIterator对象可以实现对所含元素的双向遍历:使用next()方法和previous()方法,It
33、erator接口层次,集合类,Iterator 和Enumeration存取集合中的元素可以有多种方法。对于ArrayList和Vector类,他们的元素与位置有关,所以可以用与位置相关的方法来取得元素。所有的Collection都可以用Iterator来列举元素,Vector类可以用Enumeration来列举元素。前者中还有remove方法可用,所以功能更多。An Iterator is an object that moves sequentially from one component to the next through a collection structure,provid
34、ing access to its elements.,集合类,使用Iterator接口很常见。对于实现Collection接口的类,都可以用。Iterator的方法有三个:Public boolean hasNext();Public Object next();Public remove();对于List,可以通过方法:listIterator()来得到一个ListIterator接口,从而取得元素的索引。ListIterator是Iterator的子接口,出上面三个方法外,还有:,集合类,boolean hasPrevious();Object previous();void add(O
35、bject o);void set(Object o);等等 对于Vector类,可以使用elements()方法返回一个 Enumeration接口,其方法有:boolean hasMoreElements();Object nextElement();(举例),例7-11,import java.util.*;public class TestListAllElementspublic static void main(String args)Vector h=new Vector();h.add(lst);h.add(java);h.add(c);h.add(basic);printAl
36、l(Object)h);printAll(Collection)h);printAll(List)h);printAll(Vector)h);public static void printAll(Object obj)System.out.println(obj);,public static void printAll(Collection s)Iterator it=s.iterator();while(it.hasNext()System.out.println(it.next();public static void printAll(List s)ListIterator it=s
37、.listIterator();while(it.hasNext()System.out.println(it.next();while(it.hasPrevious()System.out.println(it.previous();public static void printAll(Vector s)Enumeration e=s.elements();while(e.hasMoreElements()System.out.println(e.nextElement();,集合类,Map接口及Hashtable类Map接口提供了一组“关键字-值”的集合。A table(also cal
38、led map)is a container that allows direct access by any index type.a good analogy is a dictionary;the index variable is the word being looked up,and the element that it indexes is its dictionary definition.A table is a sequence of pairs.The first component of the pair is called key.The second compon
39、ent is called the value of its key component.A table is also called a map because we think of the keys being mapped into their values,like a mathematical function:f(key)=value.,集合类,Map接口及Hashtable类Map接口的重要实现类有:Hashtable类。Hashtable中的每个关键字的元素都实现了hashCode()方法,为每一个元素返回一个对应的值。该类的主要方法有:public void put(Obj
40、ect key,Object value);public Object get(Object key);public Object remove(Object key);public Enumeration kyes();,例7-12,import java.util.*;class TestHashtable public static void main(String args)Hashtable ht=new Hashtable();ht.put(one,new Integer(1);ht.put(two,new Integer(2);ht.put(three,new Integer(3
41、);ht.put(four,new Integer(4);ht.put(five,new Integer(5);Enumeration em=ht.keys();while(em.hasMoreElements()Object key=em.nextElement();Object value=ht.get(key);System.out.println(+key+=+value);,7.7.1 泛型,泛型(Generic)是JDK5.0增加的最重要的Java语言特性。使用泛型可以解决这种问题:程序可以针对不同的类有相同的处理办法,但这些类之间不一定有继承关系。Vector v=new Vec
42、tor();v.addElement(“one”);String s=v.elementAt(0);,7.7.2 增强的for语句,for(Photo photo:album)System.out.println(photo.toString();,import java.util.*;class Student String name;int age;public Student(String name,int age)this.name=name;this.age=age;public void printInfo()System.out.println(name:+name+age:+a
43、ge);,class EnrollmentCollectionprivate Vector students;EnrollmentCollection()students=new Vector();public boolean enroll(Student s)if(students.contains(s)return false;if(students.size()8)return false;students.add(s);return true;public boolean unenroll(Student s)if(students.contains(s)students.remove
44、(s);return true;elsereturn false;public int getTotalEnrollment()return students.size();public Student getNthStudent(int n)return(Student)students.elementAt(n);,class Course String courseName;double credits;private EnrollmentCollection enrolledStudents;Course(String name,double credits)courseName=nam
45、e;this.credits=credits;enrolledStudents=new EnrollmentCollection();public boolean enroll(Student s)return enrolledStudents.enroll(s);public boolean unenroll(Student s)return enrolledStudents.unenroll(s);public EnrollmentCollection getRegisteredStudent()return enrolledStudents;public class TestCourse
46、Vector public static void main(String args)int i;Course c=new Course(java,1.0);Student s1=new Student(lifang,20);Student s2=new Student(zhangqin,21);Student s3=new Student(zhangqin,21);c.enroll(s1);c.enroll(s2);c.enroll(s3);EnrollmentCollection ec=c.getRegisteredStudent();for(i=0;iec.getTotalEnrollm
47、ent();i+)Student s=ec.getNthStudent(i);s.printInfo();,Arrays类,主要用于对数组进行排序和搜索的类重要的方法:sort()方法binarySearch()方法,Collections类,是一个针对具有排序查找和反序等功能的类关于查找的类有:public static void sort(List list);public static void sort(List list,Comparator c);public static int bianrySearch(List list,Object key);list:要查找排序的List
48、key:要查找的对象Cimparator c:比较器,(1)若不提供Comparator,则List中的对象必须实现接口.该接口只有一个方法:int compareTo(Object)(2)提供Comparator,有两个方法:int Compare(Object o1,Object o2);boolean equals(Object obj)/判断是否相等,例7-17import java.util.*;class TestCollectionsSortpublic static void main(String args)Vector school=new Vector();school.
49、addElement(new Person(ling,21);school.addElement(new Person(xiaofang,20);school.addElement(new Person(xiaofang,18);System.out.println(school);Collections.sort(school);System.out.println(school);,class Person implements Comparable String name;int age;public Person(String name,int age)this.name=name;this.age=age;public String toString()return name+:+age;public int compareTo(Object obj)Person p1;p1=(Person)obj;if(p1.ageage)return-1;return 0;,
链接地址:https://www.31ppt.com/p-6045131.html