- 迭代器的用法:不能用集合的方法来增删元素,只能用迭代器的方法
Collection c=new ArrayList();
c.add("one");
c.add("#");
c.add("two");
c.add("#");
c.add("three");
c.add("#");
c.add("four");
c.add("#");
c.add("five");
System.out.println(c);
Iterator it=c.iterator();
/*
* boolean hasNext()
* 迭代器的该方法用来判断其遍历的集合是否还有
* 元素下一个可以取出
*/
while(it.hasNext())
{
/*
* E next()
* 通过迭代器获取集合中下一个元素
*/
String str=(String)it.next();
System.out.println(str);
if("#".equals(str))
{
//c.remove(str);
/*
* 在使用迭代器遍历集合的过程中是
* 不能通过集合的方法增删元素的,否则
* 迭代契会抛出异常
*/
it.remove();
/*
* 迭代器自身提供了一个供删除集合元素
* 的方法remove,该方法不许要传入参数,
* 删除的是使用迭代器next方法取出的元素
*/
}
}
- 数组与集合互转
1.数组转集合
String[] array={"one","two","three","four","five"};
List<String> list=Arrays.asList(array);
System.out.println(list.size());
System.out.println(list);
list.set(1, "2");//可以进行此操作,就像在操作原数组一样
System.out.println(list);
/*
* 对集合元素的操作就是对数组对应元素的操作
*/
for(String str:array)
{
System.out.println(str);
}
/*
* 从数组转换过来的集合是不能添加新元素的
* 否则会抛出不受支持的操作异常
* 因为对集合元素操作就是对原数组的操作,添加元素会
* 导致数组扩容,从而表示不了原数组
*/
// list.add("six");//不能进行此操作,因为改变原数组的大小
List<String> list1=new ArrayList<String>(list);
list1.add("six");
System.out.println("list1:"+list1);
2.集合转数组
Collection<String> c=new ArrayList<String>();
c.add("one");
c.add("two");
c.add("three");
c.add("four");
c.add("five");
System.out.println(c);
//不常用
//Object[] array=c.toArray();
String[] array=c.toArray(new String[c.size()]);
System.out.println(array.length);
“`