1. 程式人生 > >CharSequence及其子類用法總結

CharSequence及其子類用法總結

本文分析CharSequence及其幾個子類,如String、StringBuilder、StringBuffer、Editable。

1、通過反編譯來比較String和StringBuilder效能

反編譯:通過對可執行程式逆向分析,推匯出他人軟體的結構、思路、演算法、原理,甚至原始碼。

javac將Java原始碼編譯成位元組碼(二進位制檔案),該class檔案由JVM來執行。Java class可以執行在任何支援JVM的硬體平臺和作業系統。

package com.qinuli.demo;
//package語句後面必須帶分號
//函式名必須緊跟返回值型別
//在code目錄執行javac -d .\bin verbose com\qinuli\demo\First.java
//在bin目錄,生成類似等級結構。執行java -verbose com.qinuli.demo.First
public class First{
	public static void main(String[] args){
		System.out.println("Very good!");
	}
}

javap用來檢視Java編譯器生成的位元組碼。可以檢視Java程式碼在底層如何執行,判斷是否高效能以及如何提高效能。

package com.qinuli.demo;

public class First{
	public static void main(String[] args){
		System.out.println("Very good!");
		print();
		printProtected();
	}
	private static void print(){
		System.out.println("private method");
	}
	protected static void printProtected(){
		System.out.println("protected method");
	}
}
javap -c -public com.qinuli.demo.First >F://test.txt

-c除了方法宣告,輸出所有位元組碼指令。

-public只輸出public的屬性和方法,類似protected輸出protected和public,private輸出private、protected和public。

>將內容輸出到指定路徑檔案。

若彈出“編碼GBK的不可對映字元”,則可用用notepad.exe開啟Java檔案並另存為ANSI編碼。

1)具體指令為

javac Hello.java

java Hello

javap -c -private Hello

編譯指令含義:

ldc常量入棧,

astore_1出棧,

aload_1變數入棧

2)具體程式碼為

public class Hello{
	static String s = "hehe";
	public static void main(String[] args){
		String str = "a"+"c";
		String str2 = "b";
		str = str+"Google"+"XX"+str2+"YY"+s;
		//str += "Baidu";
	}
	String field = "grape";
	private void initialize(){
		String ss = "hh"+field;
		ss += "A";
		ss += "B";
		ss += "C";
	}
	private void initialize2(){
		StringBuilder sb = new StringBuilder();
		sb.append("A");
		sb.append("B");
		sb.append("C");
	}
}
3)反編譯結果




4)String執行相加操作,需要先例項化一個StringBuilder,累加完後,再執行toString。因此效能不及直接用StringBuilder

2、StringBuffer使用及String、StringBuffer、StringBuilder的差別

StringBuffer stringBuffer = new StringBuffer("laugh loud");//例項化
stringBuffer.append("good");//追加
stringBuffer.reverse();//翻轉
stringBuffer.delete(0, stringBuffer.length());//刪除
System.out.println(stringBuffer.toString());
差別:1)StringBuffer和StringBuilder在字串處理時不會生成新物件,記憶體使用優於String

2)StringBuffer是執行緒安全的,所以效率弱於StringBuilder

3、String常用方法

String str = "a.b.c.d.e.f";
//取代所有相應字元
Log.println(Log.INFO, TAG, str.replace('.', '_'));
//取代所有相應字串
Log.println(Log.INFO, TAG, str.replace(".", "_"));
//target用regular expression
Log.println(Log.INFO, TAG, str.replaceAll("\\.[b-d]{1}", "_"));
//只取代首個
Log.println(Log.INFO, TAG, str.replaceFirst("\\.", "#"));
//兩個字串相應區域匹配
Log.println(Log.INFO, TAG, "regionMatches:"+str.regionMatches(true, 1, ".b.c", 0, 3));
//String繼承3個介面(Serializable, Comparable<String>, CharSequence)
String str = null;
//全部大寫或小寫,將字串轉換為字元陣列
str.toLowerCase();//String
str.toUpperCase();//String
str.toCharArray();//char[]

//方便給字串排序,可忽略大小寫
str.compareTo("");//String
str.compareToIgnoreCase("");//String

//判斷字串是否包含指定子串
str.contains("");//CharSequence, chars
str.substring(0,1);//String
str.subSequence(0, 1);//CharSequence

//判斷倆字串是否相等
str.equals("");//Object
str.equalsIgnoreCase("");//String
str.contentEquals("");//CharSequence, chars

輸出結果:


2)示例講解String的一些方法

int的二進位制、八進位制、十進位制、十六進位制輸出;wrapper包含的幾個常量;

System.arrayCopy, Arrays.toString, getBytes(), String.valueOf, matches等方法。

public class Client {
	public static void main(String[] args) {
		//補碼錶示
		System.out.println("Integer.MIN_VALUE:"+Integer.toBinaryString(Integer.MIN_VALUE));
		System.out.println("Integer.MAX_VALUE:"+Integer.toBinaryString(Integer.MAX_VALUE));
		System.out.println("Integer.MIN_VALUE:"+Integer.toOctalString(Integer.MIN_VALUE));
		System.out.println("Integer.MIN_VALUE:"+Integer.toHexString(Integer.MIN_VALUE));
		System.out.println("Integer.MAX_VALUE:"+Integer.toString(Integer.MAX_VALUE, 8));
		System.out.println("Integer.MAX_VALUE:"+Integer.toString(Integer.MAX_VALUE));//radix=10
		
//		Float.SIZE;Float.MAX_VALUE;Float.MIN_VALUE;
//		Double.SIZE;Double.MAX_VALUE;Double.MIN_VALUE
//		Character.SIZE;Character.MAX_VALUE;Character.MIN_VALUE
//		Boolean.TYPE;Boolean.TRUE;Boolean.FALSE
//		Byte.MAX_VALUE;Byte.MIN_VALUE;Byte.SIZE
//		Short.MAX_VALUE;Short.MIN_VALUE;Short.SIZE
//		Long.MAX_VALUE;Long.MIN_VALUE;Long.SIZE
		
		System.out.println("陣列拷貝:");
		int[] arr = new int[]{1,2,3,4,5};
		int[] arr2 = new int[]{6,7,8,9,10};
		System.arraycopy(arr, 0, arr2, 2, 2);
		for(int j:arr2){
			System.out.print(j+",");
		}
		
		//列印陣列
		System.out.println(Arrays.toString(new byte[]{-127,-128,127}));
		byte[] multiple = new byte[]{'A','C',-128,-127,-64,127,64};
		System.out.println(Integer.toBinaryString(multiple[0]));//0100,0001
		StringBuilder sb = new StringBuilder();
		for(byte single:multiple){
			sb.append(single);//byte到int轉換
		}
		System.out.println(Arrays.toString(sb.toString().getBytes()));
		
		System.out.println(sb);//向上轉型為Object
		Client client = new Client();
		System.out.println(String.valueOf(client));//相當於toString
		
		String[] filenames = {"1.htm","1.1.htm","1.1.1.htm","1.2.htm","2.htm","2.1.htm",
				"4.htm","10.htm","8.htm","8.html"};
		for(int j=0;j<filenames.length;j++){
			if(filenames[j].matches("[0-9]+\\.htm")){
				System.out.println("篇:"+filenames[j]);
			}else if(filenames[j].matches("[0-9]+\\.[0-9]+\\.htm")){
				System.out.println("章:"+filenames[j]);
			}else if(filenames[j].matches("[0-9]+\\.[0-9]+\\.[0-9]+\\.htm")){
				System.out.println("節:"+filenames[j]);
			}
		}
		for(int j=0;j<filenames.length;j++){
			if(filenames[j].matches("1\\..+\\.htm")){
				//有下級目錄
				break;
			}
		}
	}
}

3)字串拼接

String string = "You son of bitch!";
string = string.concat("-").concat("_");
char[] chars = new char[string.length()];
string.getChars(0, string.length(), chars, 0);//將字串內容賦值到字元陣列
String newString = new String(chars, 0, chars.length);//將字元陣列轉化為字串
Log.d(TAG, "newString-"+newString);

4)字串池

//利用物件池,提高效率,減少記憶體佔用
//new並傳參相當於建立了倆物件,引數存入字串池
String string = new String("bastard");//查詢字串池,若字串池不存在該字串,先存入字串池;存在,直接讀取。
string.intern();//從字串池讀取
Log.d(TAG, "equal: "+(string==string.intern())+"-"+(string.equals(string.intern())));
HashMap<String, String> hashMap = new HashMap<>();//用HashMap實現字串池

4、Editable介面

//EditText是TextView的直接子類,但TextView.getText()返回CharSequence,而EditText.getText()返回Editable
//Editable介面繼承CharSequence, GetChars, Spannable, Appendable
//一個物件,鏈式
Editable editable = editText.getText();//Editable
editable.append('c');//char, CharSequence; Editable
editable.delete(0, 1);//; Editable
editable.insert(0, "c");//CharSequence; Editable

editText.setText("");//CharSequence
editable.clear();
//實現Spannable介面,如SpannableString
editable.clearSpans();
editable.removeSpan(null);
editable.setSpan(null, 0, 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
5、SpannableString

1) 用SpannableString設定區域性字型顏色和粗斜體

private void setTextAppearance(String f, String s, String t){
SpannableString ss = new SpannableString(f+s+t);
ss.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, f.length(), 
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
ss.setSpan(new ForegroundColorSpan(Color.BLUE), f.length()+s.length(), 
f.length()+s.length()+t.length(), 
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
TextView tv = (TextView) findViewById(R.id.txt);
tv.setText(ss);
}
2) 比較getString和getText的不同
//Context.getText
TextView textView = (TextView) findViewById(R.id.txt_getText);
textView.setText(getText(R.string.sometext));
//Context.getString
TextView textView2 = (TextView) findViewById(R.id.txt_getString);
textView2.setText(getString(R.string.sometext));
3) Html.fromHtml
TextView textView3 = (TextView) findViewById(R.id.txt_html);
textView3.setText(Html.fromHtml("<font color='red'>Very good!</font>"));
res/values/strings.xml檔案內容
<string name="sometext">
    <font color="blue">周杰倫</font>張靚穎<b>徐若瑄</b>
</string>

相關推薦

CharSequence及其用法總結

本文分析CharSequence及其幾個子類,如String、StringBuilder、StringBuffer、Editable。 1、通過反編譯來比較String和StringBuilder效能 反編譯:通過對可執行程式逆向分析,推匯出他人軟體的結構、思路、演算法、原

List介面與Set介面及其的詳細用法。Collection介面簡介。ArraList,LinkedList,Vector

(一)連結串列的特點:(1)這種節點關係的處理操作,核心需要一個Node類(儲存資料,設定引用)(2)在進行連結串列資料的查詢,刪除的時候需要equals()方法的支援。在實際的開發中對於這些資料的使用都有一些共性的特點:儲存進去而後取。             (二)Jav

SRS學習筆記10-SrsConnection及其分析

when red ins parse discovery bsp for port std SrsConnection類代表一個client的連接,其中封裝了st thread,用於在一個單獨的st thread裏處理一個client的服務請求. SrsConnection

UI組件之AdapterView及其(四)Gallery畫廊控件使用

convert cal instance ram scaletype 循環 reat targe 外觀 聽說 Gallery如今已經不使用了,API使用ViewPaper取代了,以後再學專研ViewPaper吧如今說說Gallery畫廊,就是不停顯示圖片的意思 Gall

UI組件:TextView及其

時間 raw 界面 realtime 字體 框圖 相對 mage 導入   TextView(文本框)   一、TextView作用類似於JLable用於在界面上顯示文本    二、TextView沒有邊框,如果需要邊框可以導入背景框的圖片,背景框可以自定義為背景顏色漸變

UI組件:ImageView及其

button 聯系人 round span 按鈕 界面 bad -a color   ImageView     用於顯示所有Drawable對象  ImageButton(圖片按鈕) 註意點:和Button的區別是:Button可以顯示文字,而ImageButton不

Java 集合-Set接口及其

允許 ret ins ict amp println out ++ || 2017-10-31 19:20:45 Set:無序且唯一 實現子類:HashSet, HashSet 此類實現 Set 接口,由哈希表(實際上是一個 HashMap 實例)支持。它不保

js中&&和||的另用法總結

&& || 用法註意:|| 和&& 可以運用在任何類型的數據上js中&&和||的另類用法總結

Scope及其介紹

AR ica oat 元素 equal mco ans font style 之前寫的文章: 關於作用域範圍Scope Scope及相關的子類如下: 同時有些Scope還繼承了Scope.ScopeListener類,如下: 1、StarImportSco

scrapy spider及其

level __init__ 常用 mit read none them csv sna 1.spider傳參   在運行 crawl 時添加 -a 可以傳遞Spider參數: scrapy crawl myspider -a category=electronics

27-集合--Set及其(HashSet+LinkedHashSet+TreeSet)+二叉樹+Comparable+Comparator+雜湊表+HashSet儲存自定義物件+判斷元素唯一的方式

一、Set 1、Set:元素不可以重複,是無序的(存入和取出的順序不一致) 2、Set介面中的方法和Collection中的方法一致 3、Set集合的元素取出方式只有一種:迭代器iterator() Set set = new HashSet(); I

C# 中Datatime用法總結

C# 中Datatime類用法總結  收集了一些記錄下來,這些有的是從網上找的,有些是自己使用到的: DateTime dt = DateTime.Now; dt.ToString();//2005-11-5 13:21:25 dt.ToFileTime().ToString();

List Set Map以及介面用法總結

Collection ├List│├LinkedList│├ArrayList│└Vector│ └Stack└SetMap├Hashtable├HashMap └WeakHashMap list 和set 有共同的父類Collection  它們的用法也是一樣的 唯

阻塞佇列BlockingQueue及其的使用

     BlockingQueues在java.util.concurrent包下,提供了執行緒安全的佇列訪問方式,當阻塞佇列插入資料時,如果佇列已經滿了,執行緒則會阻塞等待佇列中元素被取出後在插入,當從阻塞佇列中取資料時,如果佇列是空的,則執行緒會阻塞等待佇列中有新元素。本文詳細介紹了BlockingQu

Java中Map集合及其

Collection集合的特點是每次進行單個物件的儲存,如果現在要進行一對物件的儲存,就只能用Map集合來完成,即Map集合中會一次性儲存兩個物件,且這兩個物件的關係:key = value結構。這種結構的最大特點是可以通過key找到對應的value內容。1.Map介面Map

C++父強制轉換為用法

-----Base.h #ifndef _BASE_H_ #define _BASE_H_ #include<iostream> using namespace std; class subclass; class base { public: int a;

Android Activity原理以及其描述

簡介         Activity是Android應用程式元件,實現一個使用者互動視窗,我們可以實現佈局填充螢幕,也可以實現懸浮視窗。一個app由很多個Actvitiy組合而成,它們之間用intent-filter區別主次關係。下面將簡單介紹Activity以及其子類和其

UIView及其

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override poin

Android之AdapterView及其的介紹

Apater是介面卡 AdapterView 顯示一堆資料 —AbsListView —-ListView,GridView —AbsSpinner —-Gallery,Spinner ListView

定義一個圖形及其(三角形和矩形),分別計算其面積和周長。(第十週)

/*  * 定義一個圖形類及其子類(三角形類和矩形類),分別計算其面積和周長。  */ class Graphical {//父類public double width;//成員變數public double length;public double area;public double Perimeter;