1. 程式人生 > >Java學習lesson 10

Java學習lesson 10

常用類 常用方法object、scanner、string


API(應用程序編程接口)

* public final Class getClass();//返回Object的運行類(java的反射機制學)

* Class類中有一個類

*public String getName();//以String類型返回它所表示的實體(獲取當前正在運行的類 的全路徑)

* Integer類中有一個方法

public static String toHexString(int i);//將一個int類型的數據轉換成一個人十六進制的 字符串表示形式

* Object類:

類層次的根類。所有的對象(包括數組,都實現這個類的方法)

* public int hashCode();

返回該對象的哈希碼值

hashCode------->通過哈希算法(哈希表:hashtable)------>地址值(不是實際意義 上的地址)

* toString();

返回對象的一個字符串表示(返回以文本方式表式表示的一個次對象的字符串)

建議所有的子類都重些這個方法:

toString();源碼:

public String toString(){


return getClass().getName()+"@"+Integer.toHexString(hashCode());


}//隱藏this


toString()<==>對象名。 getClass().getName()+"@"+Integer.toHexString(hashCode())

如果直接對象名稱想要顯示成員變量的值,必須重些Object類中的toString方 法//Alt+Shift+b----->s(自動生成)

package object;

public class Student extends Object {
	private String name;
	private int age ;
	
	public Student() {
		super();
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
		

}


//測試類
public class ObjectDemo {
	public static void main(String[]args){
		
		
		Student st=new Student();
		System.out.println(st.hashCode());//每次運行結果不相同
		System.out.println("hello".hashCode());//字符串的hashCode值每次運行結果不變
		
	    System.out.println(st.getClass());//返回Object的運行類
	    System.out.println(st.getClass().getName());//獲取全路徑名稱
	    Student st1=new Student("弋痕夕",24);
	  //System.out.println(st1.toString());如果不重寫toString()
	  //這個方法就相當於st.getClass().getName()+"@"+Integer.toHexString(hashCode())
      //結果是object.Student@31731334
	    System.out.println(st1.toString());//重寫過後運行結果如下
	}
}

//運行結果

技術分享



* x.equals(y)//返回值為boolean類型

“==”和equals()方法的區別?

“==”默認比較地址

equals()方法底層是通過“==”來實現的;默認比較的是兩個對象的地址值,如 重寫equals方法則比較的是兩個對象的內容是否相同

源碼:

public boolean equals(Object obj){

return(this==obj);

}

package object;

public class Student1 {
	private String name;
	private int age ;
	
	public Student1() {
		super();
	}
	public Student1(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	//Shift+Alt+s——>h快捷鍵重寫equals()方法
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student1 other = (Student1) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}


public class EqualsDemo {
	public static void main(String[] args){
		//創建兩個對象
		Student1 st=new Student1("天凈沙",45);
		Student1 st1=new Student1("天凈沙",45);
		
		System.out.println(st==st1);//“==”默認比較的是兩個對象的地址:false
		Student1 st2=st;//將st指向的地址值賦給st2;所以st與st2指向同一個地址
		System.out.println(st==st2);
		
	       //System.out.println(st.equals(st1));底層是由"=="實現,不重寫則等價於“==”:false
		System.out.println(st.equals(st1));//重寫後默認this.變量:表示當下傳入的值所以返回true
	}

	
	
}

//運行結果

技術分享


* protected void finalize()throws Throwable:當垃圾回收器確定不存在對該對象的 更多引用時,由對象的垃圾回收器調用此方法,但是,什麽時候調用垃圾回收器

不確定;

* protected Object clone()創建並返回此對象的一個副本

throws CloneNotSupportedException

註意事項:

Object 類的 clone 方法執行特定的復制操作。首先,如果此對象的類不能實現接 口 Cloneable,則會拋出 CloneNotSupportedException。

* Scanner類:

創建文本掃描器(鍵盤錄入)

Scanner sc=new Scanner(System.in);(創建錄入對象)

* 開發步驟:

創建錄入對象

錄入數據

輸出

* nextInt();錄入int類型

nextLine();錄入一個字符串類型

有時候錄入時會出現異常:java.util.InputMismatchException.(輸入和想得到的 數據類型不匹配)

* public static final InputStream in;(標準輸入流)

* public static final OutputStream out;(標準輸出流)

* hasNeatXX();在錄入之前,加上判斷功能,判斷是否有下一個可以錄入的XX類型的數 據

*Scanner類的註意事項:

先錄入int;類型數據在錄入String類型數據,第二次錄入沒有接收到,直接輸出了結果

這是因為再輸入一次後回車才能輸入第二次,由於第二次輸入的是字符串,回車會導致第

二次輸入失敗。

解決方案:

在第二次輸入前重新創建鍵盤錄入對象

package scanner;

import java.util.Scanner;

public class ScannerDemo {
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		System.out.println("請輸入字符串:");
		String str=sc.nextLine();//先錄入String後錄入int類型,沒有問題
		System.out.println("請輸入整形數:");
		int num=sc.nextInt();
		System.out.println(str+"---"+num);
		System.out.println("----------------");
		
		System.out.println("請輸入整形數:");
		int num1=sc.nextInt();
		System.out.println("請輸入第二個整形數:");
		int num2=sc.nextInt();
		System.out.println(num1+"---"+num2);
		System.out.println("----------------");
		
		System.out.println("請輸入整形數:");
		int num3=sc.nextInt();//先錄入int後錄入String,由於回車才能接收數據的原因直接輸出int類型的值
		System.out.println("請輸入字符串:");
		String str1=sc.nextLine();
		System.out.println(num3+"---"+str1);
		System.out.println("----------------");
		
		System.out.println("請輸入字符串:");
		String str2=sc.nextLine();//正常輸入
		System.out.println("請輸入第二個字符串:");
		String str3=sc.nextLine();//正常輸入
		System.out.println(str2+"---"+str3);
		System.out.println("----------------");
		
		//上述問題的解決方法
		System.out.println("請輸入整形數:");
		int num4=sc.nextInt();
		System.out.println("請輸入字符串:");
		Scanner sc1=new Scanner(System.in);
		String str4=sc1.nextLine();
		System.out.println(num4+"---"+str4);
		System.out.println("----------------");		
	}

}

技術分享


*String類型:

字符串類:所有的字符串字面值(如“abc”“[”……)都作為此類的實例實現

字符串為常量,創建後其值不可以改變。

package string;

public class StringDemo {
	public static void main(String[] args) {
		//定義一個字符串常量(在字符串常量池中如果有這個字符串則給出它的地址
		//如果沒有,就重新定義一個字符串,並給出它的地址)
		String s = "hello" ;

		change(s) ;
		//輸出字符串變量
		System.out.println("s:"+s);
		
		s += "world" ;
		//s=“helloword”;並沒有改變常量池中的“hello”,是在常量池中重新開辟
		//了空間存新的放字符串“helloword”,並將他的地址賦給s;
		
		System.out.println("s:"+s);//輸出s為helloword
		
	}

	public static void change(String s) {
		//String類型作為形式參數和基本數據類型的效果一樣,無論對形參進行什
		//麽樣的操作都不會對實參產生影響
		s += "javase" ;
	}
}

技術分享


*String類常用的構造方法:

public String():表示一個空字符序列。

public String(byte[] bytes,Charset ch):默認字符集(編碼格式):GBK,如果是GBK 格式,可以不寫第二個參數

public String(byte[] bytes,int index,int length):將部分字節數組構造成一個 字符串

public String(char[] value):將字符數組構造成一個字符串

public String(char[] value,int index,int length):將部分的字符數組構造成一 個字符串

public String(String original):通過字符串常量構造一個字符串對象

獲取字符串的長度功能: public int length()

*面試題:

*數組中有沒有length()有length屬性,(字符串緩沖區:StringBuffer)中沒有 length(),字符串中有length()

*String s="hello";和String s=new String("hello");兩個有什麽區別?分別創建了幾 個對象?

第一個創建了一個對象

第二個創建了兩個對象(堆內存中有new String(),然後字符串常量池中會有一個字符 串常量"hello")

* String類的轉換功能(重點)

*byte[] getBytes():將字符串轉換字節數組


* 編碼和解碼:一定要保證編碼格式一致

編碼:

把能看懂的東西轉換成一個看不懂的東西:

String----->byte[]:public byte[] getBytes(String charsetName)

解碼:

把當前的byte[]轉成能看懂的東西(String):

byte[]----->String:public String(byte[] bytes,CharsetName ch)

package string;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class StringDemo3 {
	public static void main(String[] args) throws UnsupportedEncodingException{
	        //創建String對象空參
		String str=new String();
		//獲得Str的長度並輸出
		System.out.println("str.length():"+str.length());
		System.out.println("str:"+str);
		System.out.println("----------------");
		
		//創建對象並初始化
		String str1=new String("hello");
		System.out.println("str1.length():"+str1.length());
		System.out.println("str1:"+str1);
		
		//定義數組
		byte[] bt={65,66,67,68,69,70,};
		String str2=new String(bt);
		System.out.println("str2:"+str2);
		System.out.println("str2.length()"+str2.length());
		System.out.println("-------------------");
	
		
		String str3="明天有雨";
		byte[] bt2=str3.getBytes("utf-8");
		byte[] bt3=str3.getBytes();
		
		//編碼
		System.out.println(bt2);//輸出一個地址值,原因是沒有重toString方法
		//Arrays.toString();將變量轉化成字符串形式;源代碼重寫了toString();輸出bt2的內容
		System.out.println(Arrays.toString(bt2));
		System.out.println(Arrays.toString(bt3));
		System.out.println("-------------------");
		
		//解碼
		String str4= new String(bt2) ;//編碼格式不匹配;輸出亂碼
		System.out.println("str4:"+str4);
		String str5=new String(bt2,"utf-8");//使用“utf-8”格式編碼後面解碼也必須用“utf-8”格式
		System.out.println("str5:"+str5);
		String str6=new String(bt3);//如果使用“GBK”格式編碼,則不需要寫明第二個參數,它是默認的
		System.out.println("str6:"+str6);			
			
	}
}


技術分享


*char[] toCharArray():將字符串轉換成 字符數組 (開發中經常使用)

*static String valueOf(char[] chs):將字符數組轉換成字符串

*static String valueOf(int i):將一個int類型的數據轉換成字符串


註意:

String類中的valueOf()可以將任何數據類型轉換成字符串

*String toLowerCase():將字符串全部轉成小寫

*String toUpperCase():將字符串全部轉換成大寫

*String concat(String str):字符串拼接方法

package string;

public class StringDemo4 {
	public static void main(String[] args){
		//定義一個字符串
		String str="Helloword";
		System.out.println(str);
		//將字符串轉換成 字符數組
		char []ch=str.toCharArray();
		//遍歷數組
		for(int i=0;i<ch.length;i++){
			System.out.print(ch[i]+" ");
		}
	    System.out.println("");
		System.out.println("---------------");
		
		//將字符數字轉換成字符串
		String str1=String.valueOf(ch);
		System.out.println(str1+" ");
		//將int類型數據轉換成字符串
		String str2=String.valueOf(50);
		System.out.println(str2);
		
		//將字符串全部轉換成大寫
		System.out.println("toUpperCase:"+str.toUpperCase());
		//將字符串全部轉換成小寫
		System.out.println("toLowerCase:"+str.toLowerCase());
		
		//字符串的拼接
		String str3="---javase";
		System.out.println(str.concat(str3));
	}
	

}


技術分享


方法遞歸:方法調用本身的一種現象

三個條件:

1)需要定義個方法

2)方法必須有出口條件

3)必須有某一種規律

package homework;

public class FactorialDemo {
	public static void main(String[] args){
		int num=10;
		System.out.println("10!="+getSum(num));
		
	}	
    public static int getSum(int num){
    	         // 1!=1   2!=1*2  3!=2!*3   4!=3!*4  5!=4!*5
		//基數從一開始
		int factorial=1;
		//求階乘的和
		for(int i=1;i<=num;i++)
		{   
			//求階乘 
		    factorial*=i;
		}
     return factorial;
    } 
		
}


技術分享



Java學習lesson 10