650 likes | 858 Views
第 6 章 数组和集合类. 雷擎 qleii@sina.com 对外经济贸易大学信息学院. content. 6.1 数组 6.2 集合框架 6.3 枚举类型 实验: 数组. 6.1 数组. 6.1.1 数组的声明 6.1.2 数组的创建 6.1.3 数组元素的初始化 6.1.4 数组的引用 6.1.5 二维数组 6.1.6 数组的排序. 数组的概念. 数组由同一类型的一连串对象或基本数据组成,封装在同一个标识符(数组名称)下。 数组是对象 动态初始化 可以赋值给 Object 类型的变量
E N D
第 6 章 数组和集合类 雷擎 qleii@sina.com 对外经济贸易大学信息学院
content 6.1 数组 6.2 集合框架 6.3 枚举类型 实验:数组
6.1 数组 • 6.1.1 数组的声明 • 6.1.2 数组的创建 • 6.1.3 数组元素的初始化 • 6.1.4 数组的引用 • 6.1.5 二维数组 • 6.1.6 数组的排序
数组的概念 • 数组由同一类型的一连串对象或基本数据组成,封装在同一个标识符(数组名称)下。 • 数组是对象 • 动态初始化 • 可以赋值给Object类型的变量 • 在数组中可以调用类Object 的所有方法
数组元素 • 数组中的变量被称作数组的元素 • 元素没有名字,通过数组名字和非负整数下标值引用数组元素。 • 每个数组都有一个由 public final 修饰的成员变量:length ,即数组含有元素的个数(length可以是正数或零)
6.1.1 数组的声明 • 声明(Declaration) • Type[ ] arrayName; 或者 • Type arrayName[ ]; • 声明数组时无需指明数组元素的个数,也不为数组元素分配内存空间 • 不能直接使用,必须经过初始化分配内存后才能使用
数组声明的例子 • 例如: • int[] myIntArray; • String myStringArray[]; • Circle myCircleArray[];
6.1.2 数组的创建 arrayName=new Type[componets number]; • 用关键字new构成数组的创建表达式,可以指定数组的类型和数组元素的个数。元素个数可以是常量也可以是变量 • 基本类型数组的每个元素都是一个基本类型的变量;引用类型数组的每个元素都是对象的的引用
数组创建的例子 • 例如: int[] ai; aI=new int[10]; String[] aS; aS=new String[3]; Circle aC[]; aC=new Circle[5] • 或者可以将数组的声明和创建一并执行 int ai[]=new int[10]; • 可以在一条声明语句中创建多个数组 String[] s1=new String[3], s2=new String[8];
6.1.3 数组元素的初始化 • 数组元素的类型与声明的数组数据类型保持一致,每一个数组元素都相当于一个变量,进行需要对象初始化。 • 基本类型的数组,可以在声明数组名时,给出了数组的初始值。程序便会利用数组初始值创建数组并对它的各个元素进行初始化 。例如:int a[]={22, 33, 44, 55};
6.1.3 数组元素的初始化 • 创建数组的时,如果没有指定初始值,数组便被赋予默认值初始值。 • 基本类型数值数据,默认的初始值为0; • boolean类型数据,默认值为false; • 引用类型元素的默认值为null。 • 程序也可以在数组被构造之后改变数组元素值
数组元素初始化的例子 int[] aI; aI=new int[10]; String[] aS; aS=new String[3]; Circle aC[]; aC=new Circle[5]; int k =0 ; for(k=0;k<10;k++) { aI[k] = k*k; } aS[0] = "aaa"; aS[1] = new String("bbb"); aS[3] = new String("ccc"); for(k=0;k<5;k++) { aC[k] = new Circle(); }
6.1.4 数组的引用 arrayName[ index ] • 数组下标限制 • 下标从零开始计数,最大值为 length – 1,如果超过最大值,将会产生数组越界异常(ArrayIndexOutOfBoundsException) • 必须是 int , short, byte, 或者 char. • 元素的个数即为数组的长度,可以通过 arrayName.length引用
数组引用例子 public class MyArray { public static void main(String[] args){ int myArray[]; //声明数组 myArray=new int[10]; //创建数组 System.out.println("Index\t\tValue"); for(int i=0; i<myArray.length;i++) System.out.println(i+"\t\t"+myArray[i]); //证明数组元素默认初始化为0 //myArray[10]=100; //将产生数组越界异常 } }
数组变量名是一个引用 • 运行结果: • a1[0] = 2 • a1[1] = 3 • a1[2] = 4 • a1[3] = 5 • a1[4] = 6 public class AA { public static void main(String[] args) { int[] a1 = { 1, 2, 3, 4, 5 }; int[] a2; a2 = a1; for(int i = 0; i < a2.length; i++) a2[i]++; for(int i = 0; i < a1.length; i++) System.out.println( "a1[" + i + "] = " + a1[i]); } }
6.1.5 二维数组 • 二维数组的声明 Type[ ][ ] arrayName; 或者 Type arrayName[ ][ ]; • 二维数组的创建 arrayName = new Type[length1][length2]
二维数组例子 • int[ ][ ] a1 ; • myArray 可以存储一个指向2维整数数组的引用。其初始值为null。 • int[ ][ ] a2=new int[3][5] ; • 建立一个数组对象,把引用存储到myArray。这个数组所有元素的初始值为零。 • int[ ][ ] a3={{8,1,2,2,9}, {1,9,4}, {3, 7}}; • 建立一个数组并为每一个元素赋值。
二维数组的长度 public class AA { public static void main(String[] args) { int[][] a3 = {{1,2,3},{3,4},{5,6,7,8}}; System.out.println( a3.length); System.out.println( a3[0].length); System.out.println( a3[1].length); System.out.println( a3[2].length); } } 运行结果 3 3 2 4
int[ ][ ] myArray; myArray = new int[3][ ] ; myArray[0] = new int[3]; int[ ] x = {0, 2}; int[ ] y = {0, 1, 2, 3, 4} ; myArray[1] = x ; myArray[2] = y ; 二维数组的实现过程
6.1.6 数组的排序 • 在java的API里面实现了数组排序功能。在java.util.Arrays类有静态方法sort就是实现这个功能。
public class Test6_5 { public static void main(String[] args) { Student[] ss = new Student[] { new Student(1, "iven"), new Student(2, "tom"), new Student(3, "rose"), new Student(3, "jone") }; Arrays.sort(ss); for (int i = 0; i < ss.length; i++) { System.out.println(ss[i]); } } }
类和数组的应用举例 • String & StringBuffer
字符串基础类 • Java语言提供了两个类来进行字符串处理 • String类,字符串常量处理 • StringBuffer类,字符变量处理 • 上述字符串类,均为final类
字符串的表示和生成方法 • 字符串常量的表示 • 双引号括住的一串字符表示一个字符串常量 • 字符串常量对应一个String类型的对象实例 • 例:int len = ”Hello world!”.length();
字符串的表示和生成方法 • String类的构造方法 • 依据字符数组生成字符串常量对象 • String(char[] value); • String(char[] value, int startIndex, int numChars); • 依据字符内码数组生成字符串常量对象 • String(byte[] bytes); • String(byte[] bytes, int offset, int length); • String(byte[] ascii, int hiByte); • String(byte[] ascii, int hiByte, int offset, int count);
字符串的表示和生成方法 • StringBuffer类的构造方法 • StringBuffer(); • 默认构造方法,其初始容量为16 • StringBuffer(int length); • 指定初始容量的构造方法,其初始容量由参数length指定 • StringBuffer(String str); • 通过一个字符串常量来指定生成的字符串变量的初始内容
Creating Strings void create() { String s = “Amigo"; String t = new String(“ My friend"); } Other methods ……
Creating StringBuffers • Must use new • can create empty • can specify initial capacity • can specify initial character content void create() { StringBuffer sE = new StringBuffer(); // empty StringBuffer sC = new StringBuffer( 32); // 32 chars StringBuffer sInit= new StringBuffer(“ love"); }
字符串的访问 • 字符串访问的主要内容 • 字符串的长度、是否存在某个子串、某个指定位置的字符 …… • String对象的访问方法 • int length(); 获取字符串所包含的字符数 • char charAt(int index); 获取字符串指定位置的字符 • void getChars(int srcBegin, int end, char buf[], int dstBegin); 获取字符串指定位置区间内的字符
字符串的访问 • String对象的访问方法(续) • 检索特定子串( indexOf, lastIndexOf) • int indexOf(String str); 返回子串str在该字符串中首次出现位置,若未找到则返回-1 • int indexOf(String str, int fromIndex); 返回子串str在该字符串中索引fromIndex之后首次出现位置 • int lastIndexOf(String str); 返回子串str在该字符串中最后一次出现位置 • int lastIndexOf(String str, int lastIndex);返回子串str在该字符串中索引lastIndex之前最后一次出现位置
字符串的访问 • StringBuffer对象的访问方法 • 包含大部分String对象的访问方法,如length()、charAt()、getChars等 • 另提供方法int capacity(),获得StringBuffer对象当前容量
字符串的修改 • String对象的修改(实际上产生一个具有新的字符串内容的String对象副本) • String concat(String str); 将该字符串与str字符串相加, 产生一个新的String字符串对象 • String replace(char oldChar, char newChar); 产生一个新的String字符串对象,将该字符串中所有oldChar字符替换为newChar • String subString(int beginIndex); 获得该字符串中从beginIndex开始到字符串结束的子串 • String subString(int beginIndex, int endIndex);获得该字符串中从beginIndex开始到endIndex结束的子串
字符串的修改 • String对象的修改(续) • 字符串中字符大小写转换 • String toLowerCase(); 生成一个新的String字符串对象,将原字符串中所有字符转为小写 • String toUpperCase(); 将原字符串中所有字符转为大写
字符串的修改 • StringBuffer字符串对象的修改 • append(String str); 在原字符串末尾添加一个字符串str • StringBuffer insert(int offset, String str); 在原字符串指定的偏移量offset之后加入一个字符串str(其返回的字符串对象与原字符串对象为同一对象) • void setCharAt(int index, char ch); 修改指定索引位置上的字符为ch
字符串的修改 • 两类字符串对象修改的区别 • String字符串对象为常量字符串,其本身不能被修改,因此所谓修改是创建了一个具有修改后内容的String字符串对象副本 • StringBuffer字符串对象为可修改字符串,所有修改均在其本身对象上完成,不创建新的字符串对象
字符串的比较、转化和链接 • 字符串的比较(String对象) • 区分大小写比较, boolean equals(String str); • 不区分大小写比较, boolean equalsIgnoreCase(String str); • compareTo(Object o) • compareTo(String anotherString) • compareToIgnoreCase(String str)
字符串的比较、转化和链接 • 字符串的转化 • 数值转化为字符串, 各包装基本数据类型的类提供了相应的toString()方法 • 字符串转化为数值,String提供了valueOf(String str)的静态方法
字符串的比较、转化和连接 • 字符串的连接 • “+”运算符的重载,可实现字符串的连接 • 例:String s = “He is” + age + “years old.” • Java语言不提供运算符重载机制给编程人员,主要原因是“滥用运算符的重载将会大大降低程序的可读性”。
String s1 = "a"; String s2 = "A"; String s3 = "B"; // Check if identical boolean b = s1.equals(s2); // false // Check if identical ignoring case b = s1.equalsIgnoreCase(s2); // true // Check order of two strings int i = s1.compareTo(s2); // 32; lowercase follows uppercase if (i < 0) { // s1 precedes s2 } else if (i > 0) { // s1 follows s2 } else { // s1 equals s2 } // Check order of two strings ignoring case i = s1.compareToIgnoreCase(s3); // -1 if (i < 0) { // s1 precedes s3 } else if (i > 0) { // s1 follows s3 } else { // s1 equals s3 } Comparing Strings
Determining If a String Contains a Substring String string = "Madam, I am Adam"; // Starts with boolean b = string.startsWith("Mad"); // true // Ends with b = string.endsWith("dam"); // true // Anywhere b = string.indexOf("I am") > 0; // true
Getting a Substring from a String int start = 1; int end = 4; String substr = "aString".substring(start, end); // Str
Searching a String for a Character or a Substring String string = "madam, i am Adam"; //Characters //First occurrence of ‘a’ int index = string.indexOf('a'); // 1 // Last occurrence index = string.lastIndexOf('a'); // 14 // Not found index = string.lastIndexOf('z'); // -1 Substrings // First occurrence index = string.indexOf("dam"); // 1 // Last occurrence index = string.lastIndexOf("dam"); // 13 // Not found index = string.lastIndexOf("z"); // -1
Replacing Substrings in a String static String replace(String str, String pattern, String replace) { int s = 0; int e = 0; StringBuffer result = new StringBuffer(); while ((e = str.indexOf(pattern, s)) >= 0) { result.append(str.substring(s, e)); result.append(replace); s = e+pattern.length(); } result.append(str.substring(s)); return result.toString(); }
// Use String.valueOf() String s = String.valueOf(true); // true s = String.valueOf((byte)0x12); // 18 s = String.valueOf((byte)0xFF); // -1 s = String.valueOf('a'); // a s = String.valueOf((short)123); // 123 s = String.valueOf(123); // 123 s = String.valueOf(123L); // 123 s = String.valueOf(1.23F); // 1.23 s = String.valueOf(1.23D); // 1.23 // Use + s = ""+true; // true s = ""+((byte)0x12); // 18 s = ""+((byte)0xFF); // -1 s = ""+'a'; // a s = ""+((short)123); // 123 s = ""+123; // 123 s = ""+123L; // 123 s = ""+1.23F; // 1.23 s = ""+1.23D; // 1.23 Converting a Primitive Type Value to a String
// sample code for showing how // StringBuffer works // uses the append method public class SBE { public static void main(String args[]) { StringBuffer buf1, buf2, buf3, buf4; buf1 = new StringBuffer(); buf2 = new StringBuffer("happy birthday"); buf3 = new StringBuffer("hello"); buf4 = new StringBuffer(" Max"); System.out.println("buf1 = " + buf1); System.out.println("buf2 = " + buf2); System.out.println("buf3 = " + buf3); buf2.append(buf3); System.out.println("buf2 with buf3 =" + buf2); buf2.append(" to you!"); System.out.println("buf4 =" + buf4); } } StringBuffer example
6.2 集合框架 • 6.2.1 集合框架接口 • 6.2.2 Collection接口 • 6.2.3 List接口 • 6.2.4 Set接口 • 6.2.5 Map接口 • 6.2.6 Collection和Arrays • 6.2.7 泛型
集合框架 • Java语言的设计者对常用的数据结构和算法做了一些规范(接口)和实现(具体实现接口的类)。所有抽象出来的数据结构和算法统称为Java集合框架(Java Collection Framework)
6.2.1 集合框架接口 • Java语言的设计者对常用的数据结构和算法做了一些规范(接口)和实现(具体实现接口的类)。所有抽象出来的数据结构和算法统称为Java集合框架(Java Collection Framework)
6.2.1 集合框架接口 • Java2中的集合框架提供了一套设计优良的接口和类,使程序员操作成批的数据或对象元素极为方便。 • 这些接口和类有很多对抽象数据类型操作的API,而这是我们常用的且在数据结构中熟知的。例如Maps,Sets,Lists,Arrays 等。