`
收藏列表
标题 标签 来源
111
星期五, 十二月 04, 2015 19:40:55


采用Java的多线程机制可以使计算机资源得到更充分的使用,多线程可以使程序在同一时间内完成很多操作。

       本章讲解 进程与线程的共同点和区别、实现多线程的方法、线程的状态、对线程操作的方法、多线程的同步、线程间的通信,
以及线程生命周期的控制等内容。
        本章要点:
              了解进程和线程
               掌握实现多线程的方法
               熟悉线程的状态
               熟悉线程操作的方法
               熟悉线程同步的方法
               熟悉线程间通信的方法
      Java是少数的几种支持“多线程”的语言之一。
     大多数的程序语言只能循序运行单独的一个程序块,但无法同时运行不同的多个程序块。
     
          Java的“多线程”恰可弥补这个遗憾,它可以让不同的程序块一起运行,
   如此一来就可让程序运行的更为顺畅,同时也可达到多任务处理的目的。

   进程的特征是:

           1.一个进程就是一个执行中的程序,而每一个进程都有自己独立的一块内存空间,一组系统资源。
     在进行概念中,每一个进程的内部数据和状态都是完全独立的。
           2.创建并执行一个进程的系统开销比较大。
           3.进程是程序的一次执行过程,是系统运行程序的基本单位。
     
   线程的特征是:
         1.在Java中
   
day30_Reflact
package day30;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflactTesta {
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
		System.out.println("------通过Java反射机制得到类的包名和类名-----");
		Demo1();
		
		System.out.println();
		System.out.println("----验证所有的类都是Class类的实例对象  ----");
		Demo2();
		
		System.out.println();
		System.out.println("----通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在]----");
		Demo3();
		
		System.out.println();
		System.out.println("----通过Java反射机制得到一个类的构造函数,并实现创建带参实例对象 ----");
		Demo4();
	}
	
	public static void Demo1() {
		Person p1 = new Person();
		System.out.println("  获得Demo1包名----"+p1.getClass().getPackage().getName());
		System.out.println("  获得完整的类目----"+p1.getClass().getName());
	}
	
	
	 public static void Demo2() throws ClassNotFoundException  
	    {  
	        //定义两个类型都未知的Class , 设置初值为null, 看看如何给它们赋值成Person类  
	        Class<?> class1 = null;  
	        Class<?> class2 = null;  
	          
	        //写法1, 可能抛出 ClassNotFoundException [多用这个写法]  
	        class1 = Class.forName("day30.Person");  //设置为Person类
	        System.out.println("Demo2:(写法1) 包名: " + class1.getPackage().getName() + ","   
	                + "完整类名: " + class1.getName());  
	          
	        //写法2  
	        class2 = Person.class; //赋值成Person类   
	        System.out.println("Demo2:(写法2) 包名: " + class2.getPackage().getName() + ","   
	                + "完整类名: " + class2.getName());  
	    }  
	
	 //Demo3: 通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在] 
	 /* newInstance()实际上是把new这个方式分解为两步,
	     即首先调用Class加载方法加载某个类,然后实例化。*/
	 public static void Demo3() throws ClassNotFoundException, InstantiationException, IllegalAccessException  
	    {  
	        Class<?> class1 = null;  
	        class1 = Class.forName("day30.Person");  
	        //由于这里不能带参数,所以你要实例化的这个类Person,使用无参构造方法
	        Person person = (Person) class1.newInstance();  
	        person.setAge(24);  
	        person.setName("waxun..");  
	        System.out.println("Demo3: " + person.getName() + "    " + person.getAge());  
	    }  
	
	 //通过Java反射机制得到一个类的构造函数,并实现创建带参实例对象 
	 public static void Demo4() throws ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException  
	    {  
	        Class<?> class1 = null;  
	        Person person1 = null;  
	        Person person2 = null; 
	        Person person3 = null; 
	          
	        class1 = Class.forName("day30.Person");  
	        Constructor<?>[] constructors = class1.getConstructors();  //获取类中所有的构造方法,得到一系列构造函数集合  
	        person1 = (Person) constructors[0].newInstance(); 
	        person1.setName("yuzhou"); 
	        person1.setAge(24);  
	          
	        person2 = (Person) constructors[1].newInstance("xiner",25);  
	        person3 = (Person) constructors[1].newInstance("xiner_b",25);
	          
	        System.out.println("Demo4: " + person1.getName() + " : " + person1.getAge()  
	                + "  ,   " + person2.getName() + " : " + person2.getAge()  
	                ); 
	        System.out.println("Demo4: "+person3.getName() + " : " + person3.getAge()  
	                ); 
	          
	    }  
	 
	 
}

运行结果:
------通过Java反射机制得到类的包名和类名-----
  获得Demo1包名----day30
  获得完整的类目----day30.Person

----验证所有的类都是Class类的实例对象  ----
Demo2:(写法1) 包名: day30,完整类名: day30.Person
Demo2:(写法2) 包名: day30,完整类名: day30.Person

----通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在]----
Demo3: waxun..    24

----通过Java反射机制得到一个类的构造函数,并实现创建带参实例对象 ----
Demo4: yuzhou : 24  ,   xiner : 25
Demo4: xiner_b : 25




package day30;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;



public class ReflactTestb {
	public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException, InstantiationException, ClassNotFoundException {
		System.out.println("---- 通过Java反射机制操作成员变量, set 和 get----");
		Demo5();
		
		System.out.println("----通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等----");
		Demo6();
	}
	
	 public static void Demo5() throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException, InstantiationException, ClassNotFoundException  
	    {  
	        Class<?> class1 = null;  
	        class1 = Class.forName("day30.Person");  
	        Object obj = class1.newInstance();  
	        /*java.lang.Class<T>
	         *getDeclaredField(String name) 
	         *返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段。*/
	        Field personNameField = class1.getDeclaredField("name");  
	        /*java.lang.reflect.AccessibleObject
	         *setAccessible(boolean flag)将此对象的 accessible 标志设置为指示的布尔值。
	         */
	        personNameField.setAccessible(true);  
	        /*set(Object obj, Object value)
	         * 将指定对象变量上此 Field 对象表示的字段设置为指定的新值。*/
	        personNameField.set(obj, "宇宙歆儿");  
	         
	        //get(Object obj)返回指定对象上此 Field 表示的字段的值。
	        System.out.println("Demo5: 修改属性之后得到属性变量的值:" + personNameField.get(obj));  
	          
	    }  
	 
	 public static void Demo6() throws ClassNotFoundException{
		 Class<?> class1 = null;
		 class1 = class1.forName("day30.SuperMan");
		 //取得父类的名字
		 Class<?> class2 = class1.getSuperclass();
		 System.out.println("取得superman的父类名: "+class2.getName());
		 
		 Field[] fields = class1.getDeclaredFields();//获得所表示的类或接口的指定已声明字段
		 for(int i = 0 ; i < fields.length ; i++ ) {
			 System.out.println("类中的成员为: "+fields[i]);
		 }
		//取得类方法
		 Method[] methods = class1.getDeclaredMethods();
		 for(int i = 0;i<methods.length;i++) {
			System.out.println("函数名 : "+methods[i].getName()); 
			System.out.println("函数返回值类型:   "+methods[i].getReturnType());
			System.out.println("函数访问修饰符:" + Modifier.toString(methods[i].getModifiers()));  
	        System.out.println("函数代码写法: " + methods[i]);  
		 }
		 
		//取得类实现的接口,因为接口类也属于Class,所以得到接口中的方法也是一样的方法得到哈  
	        Class<?> interfaces[] = class1.getInterfaces();  
	        for (int i = 0; i < interfaces.length; i++) {  
	            System.out.println("实现的接口类名: " + interfaces[i].getName() );  
	        }  
		 
	 }
	      
	 
}

运行结果:
---- 通过Java反射机制操作成员变量, set 和 get----
Demo5: 修改属性之后得到属性变量的值:宇宙歆儿
----通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等----
取得superman的父类名: day30.Person
类中的成员为: private boolean day30.SuperMan.BlueHair
函数名 : isBlueHair
函数返回值类型:   boolean
函数访问修饰符:public
函数代码写法: public boolean day30.SuperMan.isBlueHair()
函数名 : setBlueHair
函数返回值类型:   void
函数访问修饰符:public
函数代码写法: public void day30.SuperMan.setBlueHair(boolean)
函数名 : fly
函数返回值类型:   void
函数访问修饰符:public
函数代码写法: public void day30.SuperMan.fly()
函数名 : walk
函数返回值类型:   void
函数访问修饰符:public
函数代码写法: public void day30.SuperMan.walk(int)
实现的接口类名: day30.ActionInterface
day29_Reflaction
http://blog.csdn.net/kubete/article/details/4493977

package day29;

import  java.awt.event.ActionListener;  
import  java.awt.event.ActionEvent;  
class  A  extends  Object  implements  ActionListener{  
	private   int  a =  3 ;  
	public  Integer b =  new  Integer( 4 ); 
	
	public  A(){
	}  
	public  A( int  id,String name){
	}  
	
	public   int  abc( int  id,String name){ 
		return   0 ;
	}  
	
	public   void  actionPerformed(ActionEvent e){
	}  
}


package day29;

import  java.lang.reflect.*;  
class  B{  
	public   static   void  main(String args[]){  
		A r = new  A();  
		Class temp = r.getClass();  
		try {  
			System.out.println("反射类中所有公有的属性" );  
			/*返回一个包含某些 Field 对象的数组,
			 * 这些对象反映此 Class 对象所表示的类或接口的所有可访问公共字段。*/
			Field[] fb =temp.getFields();  
			for ( int  j= 0 ;j<fb.length;j++){  
				Class cl = fb[j].getType();  
				System.out.println("fb:" +cl);  
			}  
  
			System.out.println("反射类中所有的属性" );  
			Field[] fa = temp.getDeclaredFields();  
			for ( int  j= 0 ;j<fa.length;j++){  
				Class cl = fa[j].getType();  
				System.out.println("fa:" +cl);  
			}  
			System.out.println("反射类中私有属性的值" );  
			Field f = temp.getDeclaredField("a" );  
			f.setAccessible(true );  
			Integer i = (Integer)f.get(r);  
			System.out.println(i);  
		}catch (Exception e){  
			e.printStackTrace();  
		}  
	}  
}   


反射类中所有公有的属性
fb:class java.lang.Integer
反射类中所有的属性
fa:int
fa:class java.lang.Integer
反射类中私有属性的值
3


这里用到了两个方法,getFields()、getDeclaredFields(),它们分别是用来获取反射类中所有公有属性和反射类中所有的属性的方法。另外还有getField(String)和getDeclaredField(String)方法都是用来过去反射类中指定的属性的方法,要注意的是getField方法只能取到反射类中公有的属性,而getDeclaredField方法都能取到。
这里还用到了Field 类的setAccessible方法,它是用来设置是否有权限访问反射类中的私有属性的,只有设置为true时才可以访问,默认为false。另外 Field类还有set(Object AttributeName,Object value)方法,可以改变指定属性的值。

http://blog.csdn.net/cnham/article/details/3086038


你这样想,编程中不是有动态和静态之分么?反射可以动态获得一个类的所有属性、方法等,
例如你定义了一个接口,实现这个接口的类有20个,程序里用到了这个实现类的地方有好多地方,如果你不使用配置文件手写的话,代码的改动量是不是很大呢,因为每个地方都要改而且不容易定位,如果你在编写之前先将接口与实现类的写在配置文件里,下次只需改配置文件,利用反射(java API已经封装好了,你直接用就可以用 Class.newInstance())就可完成。

http://1454396751.iteye.com/blog/1871384#comments
day29_Datastream
package day29;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class DataStreamTest {
	public static void main(String[] args) {
		/*分别通过DataOutputStream类的
		 * writeUTF()、writeChars()、writeBytes()方法向指定的磁盘文件中输入数据,
		 * 并通过DataInputStream类的readUTF()方法将写入的数据输出到控制台上。*/
		
		try {
			/*FileOutputStream(File file) 
			 * 创建一个向指定 File 对象表示的文件中写入数据的文件输出流。*/
			FileOutputStream fs = new FileOutputStream("G:/word.txt");
			/*DataOutputStream(OutputStream out) 
			 *创建一个新的数据输出流,将数据写入指定基础输出流。*/
			DataOutputStream ds = new DataOutputStream(fs);
			ds.writeUTF("使用writeUTF()方法写入数据");  //写入磁盘数据
			ds.writeChars("使用writeChars()方法写入数据");
			ds.writeBytes("使用writeBytes()方法写入数据");
			ds.close();
			
			/*DataInputStream(InputStream in) 
			 * 使用指定的底层 InputStream 创建一个 DataInputStream。*/
			FileInputStream fis = new FileInputStream("G:/word.txt");
			DataInputStream dis = new DataInputStream(fis);
			System.out.print(dis.readUTF());  //将文件数据输出
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

运行结果:
使用writeUTF()方法写入数据
day29_zip
package day29;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipTest {
	/*本例在zip()方法中实现使用ZipOutputStream类对文件进行压缩,在主方法中调用该方法。*/
	public static void main(String[] args) {
		ZipTest book = new ZipTest();  //创建本例对象
		try {
			book.zip("G:/hello.zip", new File("G:/hello")); //调用方法,参数为压缩后文件与要压缩文件
			System.out.println("压缩完成");//输出信息
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void zip(String zipFileName,File inputFile) throws Exception{
		FileOutputStream fos = new FileOutputStream(zipFileName);
		ZipOutputStream out  = new ZipOutputStream(fos);//创建ZipOutputStream类对象
		zip(out,inputFile,"");//调用方法
		System.out.println("压缩中...");
		out.close();//将流关闭
	}
	
	private void zip(ZipOutputStream out,File f,String base) throws Exception{//方法重载
		if(f.isDirectory()) { //测试此抽象路径名表示的文件是否是一个目录
			File[] f1 = f.listFiles(); //获取路径数组
			out.putNextEntry(new ZipEntry(base+"/"));//写入此目录的entry
			base = base.length() == 0?"":base+"/";//判断参数是否为空
			for(int i =0;i<f1.length;i++){//循环遍历数组中文件
				zip(out,f1[i],base+f1[i]);
			}
		}else{
			out.putNextEntry(new ZipEntry(base));//创建新的进入点
			FileInputStream in = new FileInputStream(f);//创建FileInput对象
			int b;
			System.out.println(base);
			while((b = in.read())!=-1) {//如果没有到达流的尾部
				out.write(b);  //将字节写入当前zip条目
			}
			in.close(); //关闭流
		}
	}
}

G:\hello\hello1.txt
G:\hello\hello2.txt
压缩中...
压缩完成

day29_java io buffer
package day29;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferTest {
	public static void main(String[] args) {
		/*向指定的磁盘中写入数据,
		并通过BufferedReader类将文件中的信息分行显示。*/
		
		String content[] = {"好久不见","最近好吗","瓦询..."};//定义字符串数组
		File file = new File("G:/word.txt");//创建文件对象
		try {
			FileWriter fw = new FileWriter(file); //创建FileWriter对象
			BufferedWriter bufw = new BufferedWriter(fw);//创建BufferedWriter类对象
			for(int k = 0;k < content.length; k++) {     
				bufw.write(content[k]);     //将字符串数组中数组中元素写入到磁盘文件中
				bufw.newLine(); //将数组中的单个元素以单行的形式写入文件
			}
			bufw.close();        //将BufferedWriter流关闭
			fw.close();          //将FileWriter流关闭
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			FileReader fr = new FileReader(file);//创建FileReader类对象
			BufferedReader bufr = new BufferedReader(fr);//创建BufferedReader类对象
			String s = null;                      //创建字符串对象
			int i = 0;
			while((s = bufr.readLine() )!= null){//如果文件的文本行数不为null,则进入循环
				i++;
				System.out.println("第"+i+"行  : "+s); //输出文件数据
			}
			bufr.close();                 //将BufferedReader流关闭
			fr.close();                   //将FileReader流关闭
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

第1行  : 好久不见
第2行  : 最近好吗
第3行  : 瓦询...
day_25Java I/Os
package day25;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileTest {
	public static void main(String[] args){
	/*使用FileOutputStream类向文件word写入信息,
	然后通过FileInputStream类将文件中的数据读取到控制台上。*/
		File file = new File("G:/asiainfo","test_zhuhw");
		try {
			FileOutputStream fio = new FileOutputStream(file);
			byte b[] = "你好呀,我是瓦询...".getBytes();
			fio.write(b);
			fio.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			FileInputStream fii = new FileInputStream(file);
			byte byt[] = new byte[1024];
			/*
			 * 从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中。
			 * public int read(byte[] b)
			 * b - 存储读取数据的缓冲区。
			 * 返回:读入缓冲区的字节总数,如果因为已经到达流末尾
			 * 而没有更多的数据,则返回 -1 */
			int len = fii.read(byt);
			/*public String(byte[] bytes,
		              int offset,
		              int length)
			通过使用平台的默认字符集解码指定的 byte 子数组,
			构造一个新的 String。新 String 的长度是字符集的函数,
			因此可能不等于该子数组的长度。
			参数:
			bytes - 要解码为字符的 byte
			offset - 要解码的第一个 byte 的索引
			length - 要解码的 byte 数 
           */
			String s = new String(byt,0,len);
			System.out.print("文件中的信息是: "+s);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
文件中的信息是: 你好呀,我是瓦询...
day30 filestream
package day25;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileTest {
	public static void main(String[] args) {
		
		File file = new File("E:/zhuhw_study","test.txt");
		/*if(file.exists()) {
		}else{
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}}*/
			try {
				FileOutputStream fs = new FileOutputStream(file); //创建FileOutputStream对象
				byte[] a = "abcdefg".getBytes();  //创建byte型数组
				fs.write(a);                          //将数组中的信息写入到文件中
				fs.close();                           //将流关闭
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
            try {
				FileInputStream fin = new FileInputStream(file); //创建FileInputStream对象
				byte[] b = new byte[1024];                       //创建byte数组
				int len = fin.read();                            //从文件中读取信息
				/*String(byte[] bytes, int offset, int length) 
				 * 通过使用平台的默认字符集解码指定的 byte 子数组,
				 * 构造一个新的 String。 
				 * bytes - 要解码为字符的 byte
				 * offset - 要解码的第一个 byte 的索引
				 * length - 要解码的 byte 数
				 * */
				System.out.print("文件中的信息是 : "+new String(b,0,len));           //将文件中信息输出
				fin.close();                                     //关闭流
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}



文件中的信息是 : 乱码显示....

以上代码由于是二进制写入,可能存在乱码,你可以使用以下代码实例来解决乱码问题:

代码案例:
package day25;
//文件名 :fileStreamTest2.java
import java.io.*;

public class fileStreamTest2{
	public static void main(String[] args) throws IOException {
		
		// 构建FileOutputStream对象,文件不存在会自动新建
		File f = new File("E:/zhuhw_study","a.txt");
		FileOutputStream fop = new FileOutputStream(f);
		
		// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
		OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
		
		// 写入到缓冲区
		writer.append("中文输入");
		
		//换行
		writer.append("\r\n");
		
		// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
		writer.append("English");
		
		//关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
		writer.close();
		
		// 关闭输出流,释放系统资源
		fop.close();
		
		// 构建FileInputStream对象
		FileInputStream fip = new FileInputStream(f);
		
		// 构建InputStreamReader对象,编码与写入相同
		InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
		

		StringBuffer sb = new StringBuffer();
		while (reader.ready()) {
			// 转成char加到StringBuffer对象中
			sb.append((char) reader.read());
			
		}
		System.out.println(sb.toString());
		// 关闭读取流
		reader.close();
		
		// 关闭输入流,释放系统资源
		fip.close();
	}
}

运行结果:
中文输入
English
day25 I/O i/o
package day25;

import java.io.File;
import java.io.IOException;

public class FileTest {
	public static void main(String[] args) {
		
		/*File(File parent, String child) 
		 *根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例
		 *在项目中创建FileTest类,在主方法中判断文件夹是否存在..txt文件,
		 *如果文件存在将其删除,不存在则创建该文件 */
		File file = new File("E:/zhuhw_study","test.txt");
		if(file.exists()) {
			file.delete();
			System.out.print("文件已被删除");
		}else{
			try {
				file.createNewFile();
				System.out.print("文件已被创建");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
}

运行结果:
文件已被删除

package day25;

import java.io.File;
import java.io.IOException;

public class FileTest {
	public static void main(String[] args) {
	
		/*获取文件夹下的..txt文件的文件名、文件长度、并判断该文件是否是隐藏文件。*/
	    File f2 = new File("E:/zhuhw_study","test2.txt");
	    System.out.println("文件的文件名:  "+f2.getName());
	    System.out.println("文件的长度: "+f2.length());
	    System.out.println("文件是否是隐藏文件: "+f2.isHidden());
	}
}

运行结果:
文件的文件名:  test2.txt
文件的长度: 0
文件是否是隐藏文件: false

java_22 泛型
package day22;

public class reviewupdown {
	public static void main(String[] args) {
		/*回归向上转型、向下转型*/
		T m = new T();
		/*向上转型*/
		m.setB(new Boolean(true));
		System.out.println(m.getB());
		
		/*向下转型*/
		m.setB(new Float(12.3));
		Float f = (Float) m.getB();
		System.out.println(f);
		
		/*“向上转型是安全的,
		 * 但是执行“向下转型”操作时用错了类型或者并没执行该操作:
		 * 并不存在语法错误,可以被编译器接受,但执行时会出现 java.lang.ClassCastException”*/
		m.setB(new Float(11.4));
		Integer i = (Integer) m.getB();
		System.out.print(i);
	}
}

class T{
	private Object B;

	public Object getB() {
		return B;
	}

	public void setB(Object b) {
		B = b;
	}
	
}
运行结果:
true
12.3
Exception in thread "main" java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer
	at day22.reviewupdown.main(reviewupdown.java:20)



代码2:
package day22;

public class GenericTest {
	public static void main(String[] args) {
		OverClass<Float> f = new OverClass<Float>(); //实例化一个Float对象
		OverClass<Integer>  c = new OverClass<Integer>();//实例化一个Integer对象
		f.setOver(11.6f);
		c.setOver(7);
		Float f2 = f.getOver();//不需要类型转换
		Integer c2 = c.getOver();//不需要类型转换
		System.out.println(f2);  
		System.out.println(c2);
		
	}
}

class OverClass<T>{    //定义泛型类
	private T over;    //定义泛型成员变量

	public T getOver() {//设置getXXX()方法
		return over;
	}

	public void setOver(T over) {  //设置setXXX()方法
		this.over = over;
	}
	
}

运行结果:
11.6
7


代码3
package day22;

public class GenericTest {
	public static void main(String[] args) {
		
		/*定义泛型类时声明数组类型*/
		
		ArrayClass<Integer> arr = new ArrayClass<Integer>();
		Integer m[] = {1,2,3,4,5};
		arr.setTt(m);
		for(int i = 0;i < arr.getTt().length;i++) {
			System.out.print(arr.getTt()[i]);
			System.out.print(" ");
		}
		
	}
}

class ArrayClass<T> {
	private T[] tt;  //定义泛型数组

	public T[] getTt() {   //获取成员数组
		return tt;
	}

	public void setTt(T[] tt) { //设置setXXX()为成员数组赋值
		this.tt = tt;
	}


}

运行结果:
1 2 3 4 5 
day20_enum 代码
package day20;

public class EnumTest {
	
	/*本例:  向枚举中添加新方法
	 * 如果打算自定义自己的方法,那么必须在enum实例序列的最后添加一个分号。
	 * 而且 Java 要求必须先定义 enum 实例。*/
	
	public enum Color{
		RED(1,"红色"),GREEN(2,"绿色"),YELLOW(3,"黄色");
		//定义私有变量
		private int inode;
		private String value;
		
		//定义构造方法,枚举类型只能为私有
		private Color(int _node,String _value) {
			this.inode = _node;
			this.value = _value;
		}
		
		//普通方法
		public static String getValue(int _inode){
			for(Color c : Color.values()) {
				if(c.getInode() == _inode) {
					return c.value;
				}
			}
			return null;
		}
		
		
		//get set方法
		public int getInode() {
			return inode;
		}

		public void setInode(int inode) {
			this.inode = inode;
		}

		
		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}

		
		
	}
	
	public static void main(String[] args) {
		System.out.print(Color.getValue(3));
	}
}


运行结果:
黄色
Iterator通过迭代方法访问类集 iterator, listiterator
package day18;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

public class IteratorTest {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		ArrayList al = new ArrayList();
		al.add("a");
		al.add("b");
		al.add("c");
		//al中的原始内容
		System.out.print("al中的原始内容:");
		Iterator itr = al.iterator();
		while(itr.hasNext()) {
			Object ob = itr.next();
			System.out.print(ob+" ");
		}
		
		System.out.print("\n");
		//在ListIterator中修改内容
		ListIterator li = al.listIterator();
		while(li.hasNext()) {
			Object ot = li.next();
			//用set方法修改其内容
			li.set(ot+"+");
		}
		//al被修改后的内容
		System.out.print("al被修改后的内容:");
		itr = al.iterator();
		while(itr.hasNext()) {
			Object obj = itr.next();
			System.out.print(obj+" ");
		}
		
		System.out.print("\n"+"将列表中的内容反向输出:");
		while(li.hasPrevious()) {
			Object ohpr = li.previous();
			System.out.print(ohpr+" ");
		}
	}
}


运行结果:
al中的原始内容:a b c 
al被修改后的内容:a+ b+ c+ 
将列表中的内容反向输出:c+ b+ a+ 
ArrayList、LinkedList、HashSet、TreeSet使用_day_16Java集合类 arraylist
一、ArrayList使用案例
代码案例1

package day18;

import java.util.ArrayList;

public class ArrayListTest {
	public static void main(String[] args) {
		ArrayList a =  new ArrayList();
		System.out.println("a.size() = "+a.size());
		a.add("A");
		a.add("B");
		//ArrayList是可变长数组
		System.out.println("....a.size() = "+a.size());
		//默认调用了toString(),很少用
		//在指定位置增加数据
		a.add(1, "C");
		System.out.println("默认调用了toString()很少用   "+a);
		
		//移除index=1的数据
		a.remove(1);
		System.out.println("移除index=1的数据"+a);
		
		a.remove("A");
		System.out.println("移除A数据   "+a);
		
		//移除数据A
		
	}
}


运行结果:
默认调用了toString()很少用   [A, C, B]
移除index=1的数据[A, B]
移除A数据   [B]


代码案例2

package day18;

import java.util.ArrayList;

public class ArrayListTest {
	public static void main(String[] args) {
			
		//程序开始创建一个整数类集
		//由于不能将原始类型存储在类集中,因此Integer的对象被创建并保存
		ArrayList a2 = new ArrayList();
		a2.add(new Integer(1));
		a2.add(new Integer(2));
		a2.add(new Integer(3));
		a2.add(new Integer(4));
		System.out.println("ArrayList中的内容:"+a2);
		
		Object b[] = a2.toArray();
		int sum = 0 ;
		for(int i =0;i < b.length; i++){
			
		/*intValue() 以 int 类型返回该 Integer 的值。*/
			sum = sum + ((Integer)b[i]).intValue();
		}
		System.out.print("数组累加的结果sum = "+sum);
		
		
	}
}


运行结果:
ArrayList中的内容:[1, 2, 3, 4]
数组累加的结果sum = 10





二、LinkedList使用案例

package day18;

import java.util.LinkedList;

public class LinkedListTest {
	public static void main(String[] args) {
		//链接列表的数据结构
		LinkedList la = new LinkedList();
		la.add("a");
		la.add("b");
		System.out.println("la的值= "+la);
	
		la.addFirst("A");
		la.addLast("B");
		System.out.println("在头尾加A/B= "+la);
		
		la.removeLast();
		System.out.println("去除最后一个B数据: "+la);
		
		//使用get/set进行改变指定位置的数据
		Object ob = la.get(0);
		la.set(0, (String)ob + "changed");
		System.out.println(la);
	}
}


运行结果:
la的值= [a, b]
在头尾加A/B= [A, a, b, B]
去除最后一个B数据: [A, a, b]
[Achanged, a, b]




三、HashSet不按顺序进行存储
package day18;

import java.util.HashSet;
import java.util.TreeSet;

public class HashSetTest {
		public static void main(String[] args) {
			HashSet ha = new HashSet();
			ha.add("A");
			ha.add("B");
			ha.add("C");
			ha.add("D");
			//元素不按顺序进行存储
			System.out.println("HashSet....不按顺序进行存储 = "+ha);
			
		}
}

运行结果:
HashSet....不按顺序进行存储 = [D, A, B, C]


四、TreeSet按升序进行存储

package day18;

import java.util.HashSet;
import java.util.TreeSet;

public class HashSetTest {
		public static void main(String[] args) {

			TreeSet ta = new TreeSet();
			ta.add("B");
			ta.add("D");
			ta.add("A");
			System.out.println("TreeSetTest...按升序存储 "+ta);
			
		}
}

运行结果:
TreeSetTest...按升序存储 [A, B, D]
Global site tag (gtag.js) - Google Analytics