JAVA语言与编程第7章工具类和算法.ppt

上传人:小飞机 文档编号:6510156 上传时间:2023-11-07 格式:PPT 页数:43 大小:226KB
返回 下载 相关 举报
JAVA语言与编程第7章工具类和算法.ppt_第1页
第1页 / 共43页
JAVA语言与编程第7章工具类和算法.ppt_第2页
第2页 / 共43页
JAVA语言与编程第7章工具类和算法.ppt_第3页
第3页 / 共43页
JAVA语言与编程第7章工具类和算法.ppt_第4页
第4页 / 共43页
JAVA语言与编程第7章工具类和算法.ppt_第5页
第5页 / 共43页
点击查看更多>>
资源描述

《JAVA语言与编程第7章工具类和算法.ppt》由会员分享,可在线阅读,更多相关《JAVA语言与编程第7章工具类和算法.ppt(43页珍藏版)》请在三一办公上搜索。

1、第7章 工具类,7.1 Java类库结构,Java类库是系统提供的已实现的标准类的集合,是Java编程的API,它可以帮助开发者方便,快捷地开发Java程序.Java类库中的类和接口基本上都封装在包中,每个包负责不同的功能,除了Java.lang包不需要引入外,其他包中的内容都需要经过import语句引入之后,才可以在程序中使用这些包中的类或接口。所有这些类的介绍和使用方法Java都提供了完善的技术文档。,7.2 java.lang包中的常用类介绍,java.lang包是java语言中最基本的包,包中的类是java类库中最低级的类。Java系统自动隐含地将这个包引入用户程序,这个包中有类,接口

2、和异常,下面是关于这个包中几个常用类的介绍:7.2.1 Object类 Object类是java程序中所有类的直接或间接父类,也是类库中所有类的父类,任何一个类都是由Object类派生出来的,它是继承树上的根结点,以下是Object类中的几个方法:public boolean equals(Object obj)用来比较两个对象是否相同,相同则返回true,否则返回false。注:所有类对象之间比较值是否相同时必须使用equals方法。例EqualsTest.javapublic String toString()用来返回当前对象本身的信息,按字符串的形式返回。在许多情况下,我们需要把一个对象

3、打印输出到一个输出流,需要一个方法来返回对象本身的信息。toString方法正是满足这个要求,若我们在自定义的类中直接调用toString方法,只能返回对象的类名和其散列码,若想返回更多信息,则要在自定义的类中重载toString方法。,7.2 java.lang包中的常用类介绍,7.2.2 Math类 Math类是一个最终类,public final class Math extends Object,它包含了常用的科学计算方法,如开方,指数运算,对数,三角函数等,可通过类名直接调用,以下是常用的属性和方法的定义:public static final double E 常数epublic

4、static final double PI 常数 三角函数:public static double sin(double)public static double cos(double)public static double tan(double)public static double asin(double)public static double acos(double)public static double atan(double)弧度,角度转换函数:public static double toRadians(double)public static double toDeg

5、rees(double),7.2 java.lang包中的常用类介绍,代数函数:public static double exp(double)以e为底的指数函数 public static double log(double)自然对数函数(对e求对数)public static double sqrt(double)计算平方根 public static double floor(double)返回与小于等于参数的最大 整数相等的double型数 public static double ceil(double)返回与大于等于参数的最小 整数相等的double型数 public static

6、 double random(double)返回一个在0.01.0之间的 double型随机数 例:RandomGenerator.java 另外三个方法:public static int abs(int)public static int max(int,int)public static int min(int,int),7.2 java.lang包中的常用类介绍,7.2.3 字符串类 字符串是一个或多个文本字符在内存中的连续排列。java中有两个类表示字符串:String类和StringBuffer类。String类适用于字符串常量,即一经创建就不能再修改的字符串。StringBuff

7、er适用于字符串变量。注:使用String类,可以做查找,比较,连接等操作,但不能在串中插入字符或修改字符串的长度。使用StringBuffer类,可以进行添加,插入,修改的操作。1.String类(1)String对象的创建 String对象可以隐式地创建,也可以显式地创建。隐式创建,例:g.drawString(“This is a String”,50,50);显式创建,例:String str=new String(“This is a String”);,7.2 java.lang包中的常用类介绍,String类的构造函数:public String()构造空字符串 public S

8、tring(String chars)构造来自另一个String对象的字符串 public String(char chars)构造来自字符数组的字符串 public String(char chars,int offset,int count)指定一个字符数组的子范围来初始化,offset指定子范围的开始点,count指定使用的字符数目(2)字符串类的常用方法 构造了String对象后,就可以调用String类的方法来获得关于该字符串的信息.public int length()返回字符串中字符的个数 例:String str=“Hello”;System.out.println(str.l

9、ength();public char charAt(int index)返回index位置的字符public void getChars(int srcBeginIndex,int srcEndIndex,char dst,int dstBeginIndex)将字符串中的字符复制到字符数组中,7.2 java.lang包中的常用类介绍,public boolean equals(Object obj)将当前字符串与形参列表中字符串比较String类还提供了一个类似的方法public boolean equalsIgnoreCase(String str)public int compareT

10、o(String str)按字母顺序比较当前字符串与参数字符串.类似方法:public int compareToIgnoreCase(String str)public boolean startsWith(String prefix)判断字符串前缀是否为参数字符串例:String str=“This is a string!”;boolean result=str.startsWith(“This”);startsWith方法的另外一种形式,在字符串指定位置开始判断是否为指定字符子串:public boolean startsWith(String str,int offset)例:“He

11、llo,world!”.startsWith(“world”,6)将返回truepublic boolean endsWith(String suffix)判断当前字符串后缀是否为参数字符串,7.2 java.lang包中的常用类介绍,public int indexOf(char ch)查找ch出现的第一个位置,若不存在,则返回-1类似方法:public int indexOf(char ch,int fromIndex)从fromIndex开始找public int indexOf(String str)查找参数指定的子串出现的第一个位置类似方法:public int indexOf(St

12、ring str,int fromIndex)public int lastIndexOf(char ch)返回ch在字符串中出现的最后一个位置类似方法:public int lastIndexOf(char ch,fromIndex);public int lastIndexOf(String str)在字符串中查找子串出现的最后一个位置类似方法:public int lastIndexOf(String str,int fromIndex)public String substring(int beginIndex)返回从beginIndex位置开始的新字符串例:“How are you?

13、”.substring(8);“Uneasy”.substring(2);“good”.substring(5);,7.2 java.lang包中的常用类介绍,public String substring(int beginIndex,int endIndex)从当前字符串中截取新字符串,beginIndex 开始位置,endIndex 结束位置的下一位.若当前字符串是str,则方法substring(beginIndex,str.length()等同于方法substring(beginIndex)例:“uneasy”.substring(2,6);“uneasy”.substring(2)

14、;public String concat(String str)把参数字符串连接到当前字符串的尾端例:”hello,”.concat(“world!”);public String replace(char oldChar,char newChar)把字符串中所有oldChar换成newChar例:String str1=“This is a string!”;String str2=str1.replace(i,x);str2的值为”Thxs xs a strxng!”public String trim()有时字符串的前面或后面有空格,trim()方法可以将这些空格去掉例:String

15、str1=“This is a string!“String str2=str1.trim();str2的值为”This is a string!”,7.2 java.lang包中的常用类介绍,public String toLowerCase()将当前字符串中所有大写字母转换为小写字母相关方法:public String toUpperCase()public char CharArray()把字符串转换为字符数组public static String valueOf(long l)这个方法有多个重载的方法,形参类型可以是其他的基本数据类型,它的功能是将基本数据类型的值转换成字符串返回.在

16、使用System.out中的方法println输出基本数据类型的数据时,系统会自动调用这个方法进行数据类型的转换,把数值变成字符串输出.public String split(String regex)将一个字符串按照指定分隔符分隔,将分隔后得到的字符串数组返回给方法例:StringCompare.java 字符串的比较 StringReverse.java StringSplit.java,7.2 java.lang包中的常用类介绍,2.2 StringBuffer类 StringBuffer类处理字符串变量,使用StringBuffer类可以改变一个字符串的值和长度,可以方便的在字符串里添

17、加字符或替换字符串里的子串.1.StringBuffer类的构造函数StringBuffer();只建立一个空串缓冲区StringBuffer(int length);建立一个长度为length的空串缓冲区StringBuffer(String str);初始化缓冲区的内容,为给定串再加上16个 字符的空间2.StringBuffer类常用的方法public StringBuffer append(String str)将str加到当前字符串对象的尾端例:StringBuffer bufferStr=new StringBuffer();bufferStr.append(“Hello,”);b

18、ufferStr.append(“world!”);,7.2 java.lang包中的常用类介绍,append()函数存在多个重载:StringBuffer append(boolean b);StringBuffer append(char c);StringBuffer append(char str);StringBuffer append(char str,int offset,int len);StringBuffer append(double d);StringBuffer append(float f);StringBuffer append(int i);StringBuff

19、er append(long l);StringBuffer append(Object obj);StringBuffer append(StringBuffer s);public StringBuffer insert(int offset,String str)在当前对象插入参数指定的字符串例:StringBuffer str=new StringBuffer(“This is a buffered string!”);str.insert(str.length(),”We are testing.”);str.insert(0,”Hello,BufferString.”);,inse

20、rt()函数也存在多个重载:StringBuffer insert(int offset,boolean b);StringBuffer insert(int offset,char c);StringBuffer insert(int offset,char str);StringBuffer insert(int offset,double b);StringBuffer insert(int offset,int b);StringBuffer insert(int offset,float b);StringBuffer insert(int offset,long b);String

21、Buffer insert(int offset,Object obj);StringBuffer insert(int index,char str,int offset,int len);public StringBuffer delete(int start,int end)删除当前字符串对象中start到end之间的子串,子串中包含start位置的字符,但不包含end位置的字符,7.2 java.lang包中的常用类介绍,public StringBuffer deleteCharAt(int index)删除当前字符串对象中指定位置的字符public StringBuffer rep

22、lace(int start,int end,String str)将当前字符串中start与end之间的子串用str替换,被替换的子串包含start位置的字符,不包含end位置的字符public StringBuffer setCharAt(int index,char ch)public StringBuffer reverse()将当前字符串中的字符序列逆转public int length()public int capacity()public void setLength(int newLength)改变当前字符串对象的长度例:StringBuffer str=new String

23、Buffer(“This is a buffered string!”);str.setLength(26);str.setLength(30);str.setLength(18);“string!”被删掉,7.2 java.lang包中的常用类介绍,public String substring(int start,int end)提取当前字符串对象中的子字符串public String toString()把可变字符串中的内容变成String类对象.实际上,在使用()打印字符串变量时,系统就自动调用了该方法例:StringBufferChars.java,7.2 java.lang包中的常

24、用类介绍,7.2.4 System类 System类是一个功能强大,非常有用的类,它提供了标准输入/输出,显示运行时的重要信息等重要工具.System类是一个final类,不能被继承.其构造函数的访问权限为private,因此它不能被实例化.System类的所有属性和方法都是static的,可用类名直接访问.1.标准输入输出public static final InputStream in标准输入public static final PrintStream out标准输出public static final PrintStream err标准错误输出 out和err都是PrintStre

25、am类的对象,可以通过print(),println()或write()方法方便地完成对各种数据类型的输出.in为InputStream类的对象,可以通过read()方法读取字节数据,7.2 java.lang包中的常用类介绍,read()方法有三种格式:public abstract int read()读取一个字节返回给方法public int read(byte b)读取若干字节放入数组b中,返回个数public int read(byte b,int offset,int count)write()方法的格式:void write(byte i)void write(byte b,in

26、t offset,int length)例:ReadTest.java,7.2 java.lang包中的常用类介绍,7.2.5 基本数据类型包装类每一个基本数据类型都对应一个数据类型类,数据类型类将基本数据类型的数据包装起来,并为其提供属性和方法,且其属性一般是静态属性.而方法一般用来操作它所对应的基本数据类型.以java.lang.Integer为例:其构造函数为:Integer(int value)Integer(String s),常用属性和方法:public static final int MAX_VALUE;最大int型数,231-1 public static final int

27、 MIN_VALUE;最小int型数,-231 public long longValue()返回封装数据的long型值 public double doubleValue()public int intValue()public static int parseInt(String s)throws NumberFomatException public static Integer valueOf(String s)throws NumberFomatException例:BasicDemo.java,作业:,1.编写一个程序,输出在一个字符串中,指定字符串出现的次数。答案:StringI

28、n.java2.编写一个方法,返回一个double型二维数组,数组中的元素通过解析字符串参数获得,如字符串参数“1,2;3,4,5;6,7,8”对应的数组为:d0,0=1.0 d0,1=2.0 d1,0=3.0 d1,1=4.0 d1,2=5.0 d2,0=6.0 d2,1=7.0 d2,2=8.0 答案:TestString.java,7.3 容器,7.3.1容器的概念阅读如下程序:public class Employee private String name,IDcard;public Employee(String name,String IDcard)this.name=name;

29、this.IDcard=IDcard;public String getName()return name;public String getIDcard()return IDcard;public String toString()return name+”t”+IDcard;public class Test public static void main(String args)Employee e1=new Employee(“Kitty”,”123”);Employee e2=new Employee(“Puppy”,”456”);Employee e3=new Employee(“

30、Teddy”,”789”);.,容器:用于存放对象的一系列类的实例,用于实现容器的类都位于java.util包中 容器API的类图结构如下:,没有顺序不可以重复,有顺序可以重复,存储“键-值”对,7.3.2 Collection接口Collection接口中定义的方法 int size();boolean isEmpty();void clear();boolean contains(Object element);boolean add(Object element);boolean remove(Object element);Iterator iterator();boolean con

31、tainsAll(Collection c);boolean addAll(Collection c);boolean removeAll(Collection c);boolean retainAll(Collection c);保留当前容器中与参数容器共有的元素 Object toArray();,Collection方法举例:import java.util.*;public class CollectionDemo1public static void main(String args)Collection c=new ArrayList();c.add(Hello);c.add(ne

32、w Integer(3);c.add(new Employee(Kitty,123);System.out.println(c.size();System.out.println(c);,Collection方法举例:public class CollectionDemo2public static void main(String args)Collection c=new HashSet();c.add(Hello);c.add(new Integer(3);c.add(new Employee(Kitty,123);c.remove(Hello);c.remove(new Integer

33、(3);(c.remove(new Employee(Kitty,123);System.out.println(c);输出结果:false Kitty 123,Collection方法举例容器类对象在调用remove,contains等方法时需要比较对象是否相等,此时会用到equals方法和hashCode方法;自定义的类需要重写equals方法和hashCode方法,以判断自定义类的对象是否相等 注意:相等的对象应具有相等的hashcode增加Employee类的equals和hashCode方法如下:public boolean equals(Object obj)if(obj inst

34、anceof Employee)Employee e=(Employee)obj;return this.name.equals(e.name),7.3.3 Iterator接口所有实现了Collection接口的容器类都有一个iterator方法,用于返回一个实现了Iterator接口的对象Iterator对象能够方便地对容器内的元素进行遍历操作Iterator接口中定义的方法:boolean hasNext();/判断游标右侧是否有元素 Object next();/返回游标右侧的元素并将游标后移一个位置 void remove();/删除游标左侧的元素,在执行完next操作之后,此 方法

35、只能执行一次,Iterator方法举例public class IteratorDemo1public static void main(String args)Collection c=new HashSet();c.add(new Employee(Kitty,123);c.add(new Employee(puppy,456);c.add(new Employee(Teddy,789);Iterator i=c.iterator();while(i.hasNext()Employee e=(Employee)i.next();System.out.print(e.getName()+);

36、注意:Iterator对象的remove方法是在遍历过程中删除元素的唯一安全的方法,7.3.4 Set接口Set是Collection接口的子接口,它本身没有提供额外的方法Set容器与数学中集合的概念相对应,Set中的元素是没有顺序的,而且不可以重复实现了Set接口的容器类有HashSet和TreeSet等,Set方法举例public class SetDemo1public static void main(String args)Collection c=new HashSet();c.add(new Integer(3);c.add(hello);c.add(new Employee(T

37、eddy,789);c.add(new Integer(3);c.add(new Integer(100);c.add(new Employee(Teddy,789);System.out.println(c.size();System.out.println(c);,Set方法举例public class SetDemo2public static void main(String args)Set s1=new HashSet();Set s2=new HashSet();s1.add(1);s1.add(2);s1.add(3);s2.add(2);s2.add(3);s2.add(4)

38、;Set s3=new HashSet(s1);s3.retainAll(s2);Set s4=new HashSet(s1);s4.addAll(s2);System.out.println(s3);System.out.println(s4);,7.3.5 List接口List是Collection接口的子接口,实现List接口的容器类中的元素是有顺序的,而且是可以重复的List容器中的每一个元素都对应一个整型序号表示位置,可以根据整型序号存取元素List容器类有ArrayList,LinkedList等常用方法如下:Object get(int index)Object set(int

39、index,Object obj)void add(int index,Object obj)Object remove(int index)int indexOf(Object obj)int lastIndexOf(Object obj),List 方法举例public class ListDemo1public static void main(String args)List l=new LinkedList();l.add(1);l.add(2);l.add(3);l.add(1,100);l.set(3,200);l.add(2);System.out.println(l);Sys

40、tem.out.println(l.get(3);System.out.println(l.indexOf(2);System.out.println(l.lastIndexOf(2);,List容器中的常用算法类java.util.Collections用一些静态方法实现了基于List容器的一些常用算法 void sort(List l);/对List中的元素进行排序 void shuffle(List l);/对List中的元素进行随机排列 void reverse(List l);/对List中的元素进行逆序排列 void fill(Object obj,List l);/用一个对象重写

41、这个List void copy(List dest,List src);/将src List的内容拷贝到dest List int binarySearch(List l,Object obj);/对于顺序的List,采用折半查找的方法查找特定对象,List常用算法举例public class ListDemo2public static void main(String args)List l=new LinkedList();for(int i=1;i=9;i+)l.add(a+i);System.out.println(l);Collections.shuffle(l);System.

42、out.println(l);Collections.reverse(l);System.out.println(l);Collections.sort(l);System.out.println(l);System.out.println(Collections.binarySearch(l,a3);注意:此例中根据什么来比较对象之间的大小呢?,7.3.6 Comparable接口所有能排序的类都实现了java.lang.Comparable接口,这个接口中只有一个方法:public int compareTo(Object obj)实现了Comparable接口的类通过实现compareT

43、o方法,来确定其对象的排序方式,当前对象=obj 返回0当前对象 obj 返回正数,Comparable接口改写Employee类,使其实现Comparable接口class Employee implements Comparable.public int compareTo(Object obj)Employee e=(Employee)obj;int result=pareTo(e.name);return result!=0?result:this.IDpareTo(e.IDcard);,Comparable接口使用新的Employee类实现下列程序:List l=new Linked

44、List();l.add(new Employee(Jack,837483);l.add(new Employee(John,747574);l.add(new Employee(Betty,743893);l.add(new Employee(Peter,938373);l.add(new Employee(John,464737);System.out.println(l);Collections.sort(l);System.out.println(l);,7.3.7 Map接口实现Map接口的类用来存储“键-值”对Map接口的实现类有HashMap和TreeMap等Map类中存储的“键

45、-值”对通过键来标识,因此键不能重复 Object put(Object key,Object value)Object get(Object key)Object remove(Object key)boolean containsKey(Object key)boolean containsValue(Object value)int size()boolean isEmpty()void putAll(Map p)void clear(),Map方法举例import java.util.*;public class MapDemopublic static void main(Strin

46、g args)Map m1=new HashMap();Map m2=new TreeMap();m1.put(one,new Integer(1);m1.put(two,new Integer(2);m1.put(three,new Integer(3);m2.put(A,new Integer(1);m2.put(B,new Integer(2);m2.put(C,new Integer(3);System.out.println(m1.size();System.out.println(m1);System.out.println(m2);System.out.println(m1.co

47、ntainsKey(three);System.out.println(m1.remove(one);m2.putAll(m1);System.out.println(m1);System.out.println(m2);,7.3.8 Auto-boxing/unboxingjdk1.5及之后的版本提供了自动的打包和解包功能,指:例:BoxDemo.java,自动将基础类型转换为对象自动将对象转换为基础类型,7.3.9 泛型引入泛型的原因解决办法好处,jdk1.4之前类型不明确,放入容器中的类型都被当做Object,从而失去了自己的类型从容器中取出时往往要进行转换,效率低,容易出错,在定义容器时,同时定义容器中对象的类型例:GenericDemo.java,增强程序的可读性和稳定性,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号