[Java] 纯文本查看 复制代码 package Text3;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class list3 {
public static void bianli1(List<U> list,int num){
for(U u:list){ //增强for循环 遍历 简单粗暴
System.out.println(u);
}
}
public static void bianli2(List<U> list,int num){
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i)); //list 是实例化产物,代表整体数据,只要输出就是全部
//贸然套一个循环是不对的., 循环内这种整体遍历,需要从头引用遍历一次
}
}
public static void paixu(List<U> list,int num){
Collections.sort(list,new Comparator<U>() {
//通过 age 大小排序
public int compare(U u1, U u2) {
int i = u1.getAge() - u2.getAge();
if(i == 0){
return u1.getAge() - u2.getAge();
}
return i;
}
});
//遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public static void del(List<U> list,int num){
//在csdn上面看到的 两个for循环判断 age属性是否重复,重复就删除,简单粗暴,,,,,,,,,,
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if(list.get(i).getAge() == list.get(j).getAge()){
list.remove(i);
}
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
/*U u = new U();
System.out.println("1 name");
u.setName(sc.nextLine());
System.out.println("1 age");
u.setAge(sc.nextInt());
Scanner sc2 = new Scanner(System.in);
U u2 = new U();
System.out.println("2 name"); //键盘录入数据
u2.setName(sc2.nextLine());
System.out.println("2 age");
u2.setAge(sc2.nextInt());
Scanner sc3 = new Scanner(System.in);
U u3 = new U();
System.out.println("3 name");
u3.setName(sc3.nextLine());
System.out.println("3 age");
u3.setAge(sc3.nextInt());*/
//设定好的数据
U u1 = new U("z", 8);
U u2 = new U("zz", 13);
U u3 = new U("zzz", 12);
U u4 = new U("zzzz", 8);
List<U> list = new ArrayList<U>();
list.add(u1);
list.add(u2);
list.add(u3);
list.add(u4);
// bianli1(list, 8);
// bianli2(list, 77);
// paixu(list, 44);
// del(list, 11);
}
}
class U{
private String name;
private int age;
public U() {
super();
// TODO Auto-generated constructor stub
}
public U(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "name=" + name + ", age=" + age + "";
}
} |