ArrayList
ArrayList:可以看作是一个能自动增加大小的。
ArrayList的toArray()返回一个数组。
Arrays.asList()返回一个列表。
迭代器(Iterator)提供了一种通用的方式来访问集合中的元素。
public class Listline {
public static void main(String[] args) {
List list=new ArrayList();
list.add("哈哈哈哈"); //添加元素
list.add("我是老二哦");
list.remove(0);//删除指定元素
list.clear();//删除所有元素
print(list);
}
publice static void del(){
// 删除所有元素
while(true){
boolean remove = list.remove("bcd");
if(!remove){
break;
}
}
}
//输出数组所有元素
private static void print(List list) {
for (int i = 0; i<list.size();i++) {
System.out.println(list.get(i));
}
}
}
HashSet
实现Set接口的hashtable(哈希表),依靠HashMap来实现的。
我们应该为要存放到散列表的各个对象定义hashCode()和equals()。
public class ListTest {
public static void main(String[] args) {
Set set=new HashSet<>();
set.add(new Student("小王",10,"男"));
set.add(new Student("小李",15,"女"));
set.add(new Student("李四",18,"男"));
print(set);
}
private static void print(Set set) {
Iterator it=set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
public class Student {
private String name;
private int age;
private String sex;
public Student(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Stident [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
利用for循环遍历数组
for (int i = 0; i<list.size();i++)
{
System.out.println(list.get(i));
}
也可以使用foreach循环遍历集合元素。
格式:for(元素类型 t 元素变量 x : 遍历对象A) {
// 方法
}