java-集合和数组的转换


1、数组变集合的方法:Arrays.asList()
返回的集合,不能进行增、删操作.抛出异常:UnsportedIOperationExcep<wbr>tion</wbr>

思想:
通过操作集合的方式来操作数组.

2、集合变数组:Collection的toArray()方法,传一个集合对象,长度小于集合的size,则系统自动新声明一个集合.所以数组的长度最好跟集合长度一致.

增强for循环语句,需要有被遍历的目标(collection或数组).

import java.util.*;
class ArraysDemo
{
<wbr>public static void main(String[] args)<br><wbr>{<br><wbr><wbr>arrayToList();<br><wbr><wbr>listToArray();<br><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr>public static void arrayToList()<br><wbr>{<br><wbr><wbr>String [] str = {"abc", "def", "cf"}; //引用数据类型,将数组中的每个原始存入List.<br><wbr><wbr>//int[] str = {1,2,3};<wbr> //基本数据类型的数组转为List,将整个数组作为一个元素存入List,所以输出的size为1;<br><wbr><wbr>//List list = Arrays.asList(str);<br><wbr><wbr>//System.out.println(list.size());<br><wbr><wbr>List &lt;String&gt; list = Arrays.asList(str)<wbr>;<br><wbr><wbr>//list.add("cd");<wbr> //错误,不能增加删除,因为数组的长度是固定的.抛出异常:UnsportedIOperationExcep<wbr>tion<br><wbr><wbr>for (Iterator it = list.iterator(); it.hasNext(); )<br><wbr><wbr>{<br><wbr><wbr><wbr>System.out.println(it.next());<br><wbr><wbr>}<br><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr>public static void listToArray()<br><wbr>{<br><wbr><wbr>ArrayList &lt;String&gt; list = new ArrayList&lt;String&gt;();<br><wbr><wbr>list.add("aa");<br><wbr><wbr>list.add("bb");<br><wbr><wbr>list.add("cc");<br><wbr><wbr>String [] str = list.toArray(new String[list.size()]);<wbr> //参数:数组对象的长度,如果比list的size小,JVM需要重新声明一个数组,所以长度最好跟list的size保持一致.<wbr>超过list的size,超出的元素均为null<br><wbr><wbr>for (String s : str)<br><wbr><wbr>{<br><wbr><wbr><wbr>System.out.println(s);<br><wbr><wbr>}<br><wbr>}<br> }<br></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

你可能感兴趣的:(java)