Collection
package Array.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
public class collection1 {
public static void main(String[] args) {
Collection<String> c=new ArrayList<>();//多态写法
//1添加元素
c.add("java1");
c.add("java2");
c.add("java3");
c.add("javad");
System.out.println(c);
//2把集合转为数组public object[] toArray
//System.out.println(Arrays.toString(c.toArray()));
Object[] a=c.toArray();
System.out.println(Arrays.toString(a));
String[] b=c.toArray(new String[c.size()]);
System.out.println(Arrays.toString(b));
//3把一个集合中数据倒入另一个集合中
Collection<String> f=new ArrayList<>();
f.add("s1");
f.add("s2");
Collection<String> g=new ArrayList<>();
g.add("s3");
g.add("s4");
f.addAll(g);
System.out.println(f);
System.out.println(g);
}
}
[java1, java2, java3, javad]
[java1, java2, java3, javad]
[java1, java2, java3, javad]
[s1, s2, s3, s4]
[s3, s4]
Iterator
增强for![](https://i-blog.csdnimg.cn/direct/50ef4658b1b04be4857090058bd7d98b.png)
Lambda遍历
集合中存储是元素对象的地址----对象
package Array.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.function.Consumer;
public class iterotor {
public static void main(String[] args) {
Collection<String> a=new ArrayList<>();
a.add("大");
a.add("的");
a.add("都");
//1从集合对象获取迭代器对象
Iterator<String> e=a.iterator();
System.out.println(e.next());
System.out.println(e.next());
System.out.println(e.next());
System.out.println(e.next());//出现异常
//2使用循环结合迭代器遍历集合
while (e.hasNext()){
String d=e.next();
System.out.println(d);
}
// 3增强for循环
for (String s : a) {
System.out.println(s);
}
String[] name={"地遁","大","方法"};
for (String g : name) {
System.out.println(g);
}
//4defoult void forEach(Consumer<? super T>action); 结合LAmbda表达式遍历结合
a.forEach(new Consumer<String>() {
@Override
public void accept(String h) {
System.out.println(h);
}
});
a.forEach((String h)->{
System.out.println(h);
});
a.forEach(h-> {
System.out.println(h);
});
a.forEach(h -> System.out.println(h));
a.forEach(System.out::println);
}
}