2019-03-18 String[]和List的區(qū)別及相互轉(zhuǎn)換

Hello,everybody。好幾天不見啦,我一直在想著怎么整場大戲,琢磨寫個好點的文章。(其實是因為玩了一個星期,emmmm,因為懶)。

1.兩者的區(qū)別
結(jié)構(gòu)方面:
List< String >:泛型,非定長,可變。

String[]:數(shù)組,定長,不可變。

使用方面:
他們的作用一樣,但是靈活性不一樣。
List< String >是可以方便使用的,如果不能確定數(shù)組的長度,或者需要不斷的像中間插入一個字符串,可以用List< String >。
String[]是定長的,如果能確定字符串?dāng)?shù)組的長度,可以使用String[]。

2.兩者的相互轉(zhuǎn)換
先看代碼:

public class test {
public static void main(String[] args) {
//定義一個字符長度為5的字符串
String[] strings = new String[5];
strings[0] = "a";
strings[1] = "b";
strings[2] = "c";
strings[3] = "d";
strings[4] = "e";

//調(diào)用Arrays中的asList方法將String[]轉(zhuǎn)化為List<String>
List<String> list = Arrays.asList(strings);
System.out.println("list<String>:"+list.toString());

//調(diào)用toArray方法將List<String>轉(zhuǎn)化為String[]
String[] strs = list.toArray(new String[]{});
System.out.println("String[]:"+Arrays.toString(strs));

}
}

輸出的結(jié)果是:

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容