JAVA学习提高之---- List toArray学到的

最近结合一个事例掌握到ArrayList 的方法toArray()的使用。

方法:把一字符串按“,”分隔符分隔成一数组

 

方法一:

public static String[] readConfig(String inputStr){ StringTokenizer stk = new StringTokenizer(inputStr, ","); ArrayList list = new ArrayList(); int lineNum = 0; while(stk.hasMoreTokens()){ String s = stk.nextToken(); list.add(s); lineNum ++; } String[] returnStr = new String[lineNum] ; for(int i=0;i<lineNum;i++){ returnStr[i] = (String)list.get(i); } return returnStr; 

方法二:

public static String[] readConfig(String inputStr){ StringTokenizer stk = new StringTokenizer(inputStr, ","); ArrayList list = new ArrayList(); int lineNum = 0; while(stk.hasMoreTokens()){ String s = stk.nextToken(); list.add(s); lineNum ++; } Object[] o = list.toArray(); int leng = o.length; String[] reStr = new String[leng] ; for(int i=0;i<o.length;i++){ reStr[i] = o[i].toString(); } return reStr; }

方法三:

public static String[] readConfig(String inputStr){ StringTokenizer stk = new StringTokenizer(inputStr, ","); ArrayList list = new ArrayList(); int lineNum = 0; while(stk.hasMoreTokens()){ String s = stk.nextToken(); list.add(s); lineNum ++; } String[] a = new String[lineNum]; return (String[])list.toArray(a); }

前面两种方法从list到string[]都经过了复杂的转换,而第三种方法使用list的toArray方法很容易进行了转化。对于集合类与数组的相互转化很有用。

你可能感兴趣的:(java,list,object,String)