本帖最后由 中关村阿旺 于 2013-10-19 20:44 编辑
- package demo3;
- import java.util.*;
- class Student implements Comparable<Student>
- {
- public int compareTo(Student s)
- {
- int num=name.compareTo(s.name);
- if(num==0)
- return new Integer(id).compareTo(new Integer(s.id));
- return num;
- }
- private String id;
- private String name;
- public String getId()
- {
- return id;
- }
- public String getName()
- {
- return name;
- }
- Student(String id,String name)
- {
- this.id=id;
- this.name=name;
- }
- public String toString()
- {
- return id+"→→→"+name;
- }
- }
- class NewComparator implements Comparator<Student>
- {
- public int compare(Student s1,Student s2)
- {
- int num=new Integer(s1.getId()).compareTo(new Integer(s2.getId()));
- if(num==0)
- return s1.getName().compareTo(s2.getName());
- return num;
- }
- }
- class CollectionsDemo3
- {
- public static void print(List<Student> list)
- {
- for (Iterator<Student> it=list.iterator();it.hasNext() ; )
- {
- Student s=it.next();
- System.out.println(s);
- }
- System.out.println("========================================");
- }
- public static void main(String[] args)
- {
- List<Student> list=new ArrayList<Student>();
- list.add(new Student("02","lisi"));
- list.add(new Student("03","wangwu"));
- list.add(new Student("01","zhangsan"));
- list.add(new Student("03","wangwu"));
- list.add(new Student("04","zhaoliu"));
- list.add(new Student("05","zhangsan"));
- System.out.println("原集合是:");
- print(list);
- //使用另一个值替换列表中出现的所有某一指定值。
- Student s1=new Student("03","wangwu");
- Student s2=new Student("06","tianqi");
- boolean replace=Collections.replaceAll(list,s1,s2);
- System.out.println("是否成功替换:"+replace);
- System.out.println("现集合是:");
- print(list);
- System.out.println("*************************************");
- List<String> list2=new ArrayList<String>();
- list2.add("abcd");
- list2.add("ahter");
- list2.add("sfqag");
- list2.add("adgw");
- list2.add("abcd");
- list2.add("gfjf");
- System.out.println("原集合是:"+list2);
- Collections.replaceAll(list2,"abcd","haha");
- System.out.println("替换后的集合是:"+list2);
- }
- }
复制代码 为什么String类型的数据可以替换成功,而我写的Student类就是不行呢?!! |
-
有问题.png
(69.64 KB, 下载次数: 44)
为什么就是替换不了呢?
|