1.使用Arraylist,记录一组student对象,实现遍历,查询,删除,并用Collections实现排序
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
public class student {
private String name;
private int age;
public student(String name,int age)
{
this.age=age;
this.name=name;
}
public static void main(String args[])
{
//构造放students的容器
ArrayList<student>students=new ArrayList<>();
//给容器添加对象
students.add(new student("Jone",25));
students.add(new student("Alice",22));
students.add(new student("Bob",19));
//遍历
printAll(students);
//查询
findname(students,"Bob");
//删除
removestudent(students,"Bob");
//collections 排序
Collections.sort(students,(S1,S2)->S1.age-S2.age);
System.out.println("排序之后");
printAll(students);
}
//遍历
//增强性for循环
public static void printAll(ArrayList<student>students)
{
for(student a:students)
{
System.out.println(a.name);
}
}
//查询
public static student findname(ArrayList<student>students,String searchname)
{
for(student a:students)
{
if(a.name.equals(searchname))
{
return a;
}
}
return null;
}
public static void removestudent(ArrayList<student>students,String removename)
{
student a=findname(students,removename);
if(a!=null)
{
students.remove(a);
}
}
}
2.set :hashset和treeset
import java.util.*;
public class useset{
public static void main(String args[]){
HashSet<String>h1=new HashSet<String>():
TreeSet<String>t1=new TreeSet<String>():
TreeSet<String>t2=new TreeSet<String>((o1,o2)->-o1.compareTo(o2);):
//add值
for(int i=5;i>0;i--) h1.add("string"+i);
for(int i=5;i>0;i--) t1.add("string"+i);
for(int i=5;i>0;i--) t2.add("string"+i);
//遍历
//增强性for循环
for(String s:h1)
{
System.out.println(s+",");
}
//iterator遍历器遍历
Iterator<String>i1=t1.iterator();
while(i1.hasNext())
{
System.out.println(i1.next()+",");
}
}
]