Java集合的运用

3.假设顺序列表ArrayList中存储的元素是整型数字1~5,遍历每个元素,将每个元素顺序输出。(你能想到的所有方式)

public static void main(String[] args) {
        //Collection
        Collection c = new ArrayList();
        c.add(1);
        c.add(2);
        c.add(3);
        c.add(4);
        c.add(5);
        //collection 方法1
        for (int i = 0; i < c.size(); i++) {
            ArrayList a = (ArrayList) c;
            Object o = a.get(i);
            System.out.print(o+" ");
        }
        System.out.println();
        System.out.println("----------------------");
        //collection 方法2
        for (Object o : c) {
            System.out.print(o+" ");
        }
        System.out.println();
        System.out.println("----------------------");
        //collection 方法3
        Iterator iterator = c.iterator();
        while (iterator.hasNext()){
            Object next = iterator.next();
            System.out.print(next+" ");
        }
        System.out.println();
        System.out.println("----------------------");
        //List
        List list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        //List 方法1
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i)+" ");
        }
        System.out.println();
        System.out.println("-------------");
        //List 方法2
        for (Object list1 : list) {
            System.out.print(list1+" ");
        }
        System.out.println();
        System.out.println("----------------------");
        //List 方法3
        Iterator iterator1 = list.iterator();
        while (iterator1.hasNext()){
            Object next = iterator1.next();
            System.out.print(next+" ");
        }
    }

请添加图片描述

4.生成10个1到20之间的不重复的随机数

public static void main(String[] args) {
        Set set = new HashSet();
        while (set.size()<10){
            int i = (int) (Math.random()*20+1);
            set.add(i);
        }
        System.out.println(set);
    }

请添加图片描述

5.用一个大集合存入20个随机数字,然后筛选其中的偶数元素,放到小集合当中然后进行遍历输出

public static void main(String[] args) {
        Set set1 = new HashSet();
        while (set1.size()<20){
            Random r = new Random();
            set1.add(r.nextInt(100));
        }
        System.out.println(set1);
        Set set2 = new HashSet();
        for (Object o :set1) {
            Integer a = (Integer) o;
            if(a%2==0){
                set2.add(a);
            }
        }
        System.out.println(set2);

    }

请添加图片描述

6.ArrayList去除集合中字符串的重复值(字符串的内容相同)

public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add("hello");
        arrayList.add("world");
        arrayList.add("java");
        arrayList.add("HelloWorld");
        arrayList.add("hello");
        System.out.println(arrayList);
        ArrayList arrayList2 = new ArrayList();
        for (Object o:arrayList) {
            if (!arrayList2.contains(o)){
                arrayList2.add(o);
            }
        }
        System.out.println(arrayList2);
    }

请添加图片描述

7.创建两个Set集合,判断这两个集合是否有交集,并打印出他们的交集

public static void main(String[] args) {
        Set set1 = new HashSet();
        Set set2 = new HashSet();
        set1.add("hello");
        set2.add("hello");
        set1.add("world");
        set2.add("world");
        set1.add("java");
        set2.add("python");
        System.out.println("set1 = "+set1);
        System.out.println("-------------------");
        System.out.println("set2 = "+set2);
        System.out.println("-------------------");
        //方法一
        Set set3 = new HashSet();
        for (Object o :set1) {
            if (set2.contains(o)){
                set3.add(o);
            }
        }
        System.out.println("set3 = " + set3);
        //方法二
        System.out.println(set1.retainAll(set2));
        System.out.println(set1);
    }

请添加图片描述

注意逻辑

8.将1-10按照奇数在前偶数在后,奇数正序,偶数倒叙的方式保存到Set集合中(排序)

public static void main(String[] args) {
    Set set = new TreeSet(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            Integer a1= (Integer) o1;
            Integer a2= (Integer) o2;
            {
                //降序
                if (a1 % 2 == 0 && a2 % 2 == 0) {
                    return a2 - a1;
                }
                //升序
                if (a1 % 2 == 1 && a2 % 2 == 1) {
                    return a1 - a2;
                }
                //前偶后奇 换位
                if (a1 % 2 == 0 && a2 % 2 != 0) {
                    return 1;
                }
                //前奇后偶 不换
                if (a1 % 2 != 0 && a2 % 2 == 0) {
                    return -1;
                }
            }
            return 0;
        }
    });

    for (int i = 1; i <=10; i++) {
        set.add(i);
    }
    System.out.println("set = " + set);
}

请添加图片描述

9.将学生按照成绩保存到集合中,并且名字叫tom的学生不管考多少分都位于班级的第一位

public class Demo6 {
    public static void main(String[] args) {
        Set set = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                //o1新值o2老值
                Student personNew = (Student) o1;
                Student personOld = (Student) o2;
                {
                    String s = "tom";
                    //tom
                    if (personNew.getName().equals(s)&&!personOld.getName().equals(s)){
                        return -1;
                    }
                    if (!personNew.getName().equals(s)&&personOld.getName().equals(s)){
                        return 1;
                    }
                    if (!personNew.getName().equals(s)&&!personOld.getName().equals(s)){
                        Integer personNew_score = ((Student) o1).getScore();
                        Integer personOld_score = ((Student) o2).getScore();
                        return personOld_score-personNew_score;
                    }
                    if (personNew.getName().equals(s)&&personOld.getName().equals(s)){
                        Integer personNew_score = ((Student) o1).getScore();
                        Integer personOld_score = ((Student) o2).getScore();
                        return personOld_score-personNew_score;
                    }
                }
                return 0;
            }
        });

        set.add(new Student("tom",60));
        set.add(new Student("tom",70));
        set.add(new Student("rh",80));
        set.add(new Student("zzb",100));

        for (Object o : set) {
            System.out.println(o);
        }


    }
}
class Student{
    private String name;
    private int score;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return score == student.score && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, score);
    }
}

请添加图片描述

10.编写一个学生管理类,可以添加学生(学号要有唯一性)、删除学生、查看学生信息,使用List集合来实现

public class StudentMange {
    static List list = new ArrayList();
    public static void main(String[] args) {
        addStudent(new Student2("tom",1));
        addStudent(new Student2("tom",2));
        addStudent(new Student2("zzb",3));
        System.out.println(list);
        addStudent(new Student2("jim",1));
        System.out.println(list);
        deleteStudent(2);
        System.out.println(list);
        deleteStudent(4);
        showStudent(1);
        showStudent(4);
    }

    private static void addStudent(Student2 student2) {
        for (Object o : list) {
            Student2 addstudent = (Student2) o;
            if (student2.getSno()==addstudent.getSno()){
                System.out.println("该学号存在 无法添加");
                return;
            }
        }
        list.add(student2);
    }
    private static void deleteStudent(int id ) {
        Student2 stu = null;
        for (Object o : list) {
            Student2 addstudent = (Student2) o;
            if (id==addstudent.getSno()){
                stu=addstudent;
            }else {
                continue;
            }
        }
        if (stu==null){
            System.out.println("不存在该学生");
        }else {
            list.remove(stu);
            System.out.println("删除成功");
        }
    }
    private static void showStudent(int id) {
        Student2 stu = null;
        for (Object o : list) {
            Student2 addstudent = (Student2) o;
            if (id==addstudent.getSno()){
                stu=addstudent;
            }else {
                continue;
            }
        }
        if (stu==null){
            System.out.println("不存在该学生");
        }else {
            System.out.println(stu);
        }
    }
}
class Student2{
    private int sno;
    private String name;

    public Student2() {
    }

    public Student2(String name, int sno) {
        this.sno=sno;
        this.name=name;
    }

    public int getSno() {
        return sno;
    }

    public void setSno(int sno) {
        this.sno = sno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "sno=" + sno +
                ", name='" + name + '\'' +
                '}';
    }
}

请添加图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
求交集和并集的线性算法(原创) 对于给定的两个集合,使用哈希表可以在线性时间复杂度内得到他们的交集和并集,具体说明如下: 假设有集合A={1, 7, 5, 13, 9, 10, 11}, B={5, 7, 10, 1, 18, 12}, 1)求交集,需要得到结果:A∩B={1, 5, 7,10} 思路如下: ①建立一个哈希表(HashTable),其键(KEY)表示集合中数字的值,其值(VALUE)表示集合中数字出现的次数 ②遍历集合A,将集合中的每个数字(KEY)插入哈希表,每个数字的出现次数(VALUE)设置为1 ③遍历集合B,对于集合中的每个数字: 如果哈希表中已经存在该数字,将对应的VALUE改为2 如果哈希表中不存在该数字,忽略 ④遍历哈希表,输出VALUE为2的数字,即得到A和B的交集 2) 求并集,需要得到结果:AUB={1,5,7,9,10,11,12,13,18} 思路如下: ①建立一个哈希表(HashTable),其键(KEY)表示集合中数字的值,其值(VALUE)可以无视 ②遍历集合A,将集合中的每个数字(KEY)插入哈希表 ③遍历集合B,对于集合中的每个数字: 如果哈希表中已经存在该数字,忽略 如果哈希表中不存在该数字,将这个数字插入哈希表 ④遍历哈希表,输出哈希表中的每个KEY,即为A和B的并集 上面以两个集合为例说明了交集和并集的求法,事实上,上述算法可以很方便的扩展到3个或3个以上的集合 的求交集和求并集。另外求并集时,由于哈希表的值(VALUE)部分不需要用到,所以这个数据结构也可以更换为 哈希集(HashSet)。 转载请注明出处。 VB中HashTable 2012-08-20 14:43:21| 分类: asp.net|举报|字号 订阅 首先定义一个hashtable Dim hstl As New Hashtable hstl.Add(key, value) 'java是用.put MS开始全面模仿java 这说说vb.net中的hashtable基本用法: 添加值:hstl.add(key,value) 通过key取值: hstl.Item(key).ToString 判断是否含有Key: ContainsKey(key) 判断是否含有value: ContainsValue(value) 遍历hashtable: Dim de As DictionaryEntry '泛型类 For Each de In hstl console.write(de.key & de.value) Next de hashtable不支持通过value取key. 求2个集合的交集 第一种方法 最简单、粗暴的循环遍历2个集合,判断如果有相同的元素就取出来。假设集合1的长度为M,集合2的长度为N,那么,时间复杂度为:O(M*N) 代码: public static List<string> GetIntersection(List<string> list1, List<string> list2) { List<string> list3 = new List<string>(); //第一种方法:循环遍历 //O(n×m) for (int i = 0; i < list1.Count; i++) { for (int j = 0; j < list2.Count; j++) { if (list1[i]==list2[j]) { list3.Add(list1[i]); } } } return list3; } 第二种方法 利用hash这种很有用的数据结构来实现。我们知道,hash的特点之一就是不允许有重复元素,即hash表中的元素都是唯一的。所以,我们的思路就是:先把第一个集合的所有元素都放进hashSet中,时间复杂度O(M);再把第二个集合中的元素放进hashSet中,如果有重复元素,就是这2个集合的交集,时间复杂度为O(N)。即总的时间复杂度从O(M*N)降低到了O(M+N)。 代码: public static List<string> GetIntersection2(List<string> list1, List<string> list2) { //第二种方法:hash List<string> list3 = new List<string>(); HashSet<string> hashSet = new HashSet<string>(); foreach (string item in list1) { hashSet.Add(item); } foreach (string item in list2) { if (hashSet.Add(item) == false) { list3.Add(item); } } return list3; } 测试 代码: static void Main(string[] args) { List<string> list1 = new List<string>(); list1.Add("apple"); list1.Add("banana"); list1.Add("pear"); list1.Add("orange"); list1.Add("grape"); List<string> list2 = new List<string>(); list2.Add("nokia"); list2.Add("sumsung"); list2.Add("htc"); list2.Add("apple"); list2.Add("orange"); List<string> list =new List<string>(); //test for two set join //list = TwoSetsIntersection.GetIntersection(list1, list2); list = TwoSetsIntersection.GetIntersection2(list1, list2); foreach (string item in list) { Console.Write(item + "\t"); } } 总结 hash的另一个特点是查找效率为O(1),惊人的高! 对于这道题目要是算出来O(M*N)的同学就应该补课了。出来混,迟早要还的。 HashSet<T>类 HashSet<T>类主要是设计用来做高性能集运算的,例如对两个集合求交集、并集、差集等。集合中包含一组不重复出现且无特性顺序的元素。 HashSet<T>的一些特性如下: 1、HashSet<T>中的值不能重复且没有顺序。 2、HashSet<T>的容量会按需自动添加。 构造方法: HashSet() 默认相等比较器创建一个空的新实例。 HashSet(IEnumerable<T> collection)  把指定集合中的collection中的数据复制到集中 HashSet(IEqualityComparer<T> comparer)  使用指定的相等比较器创建一个空的新实例 HashSet(IEnumerable<T> collection,IEqualityComparer<T> comparer)  使用指定的比较器实例化数据,且将指定集合中的元素复制到集合中。 因为HashSet<T>是专门设计来做集合运算的,因此它提供的方法中有不少是和集合运算相关的。 以下给出它的一些常用方法介绍 成员        类型        说明 Add        方法        将指定的元素添加到集合中 Clear        方法         清空集合中的所有元素 Contains     方法         确定某元素是否在HashSet<T>中 Exists       方法         确定HashSet<T>是否包含于指定条件相匹配的元素 ExceptWith    方法         从当前HashSet<T>移除指定集合中的所有元素 IntersectWith   方法        修改当前的HashSet<T>对象,以仅包含该对象和指定集合中存在的元素 IsProperSubsetOf  方法        确定HashSet<T>对象是否为指定集合的真子集 IsProperSupersetOf 方法        确定HashSet<T>对象是否为指定集合的真超集 IsSunsetOf     方法         确定HashSet<T>对象是否为指定集合的子集 IsSupersetOf    方法         确定HashSet<T>对象是否为指定集合的超集 Remove      方法         从HashSet<T>对象中移除指定的元素 RemoveWhere   方法         从HashSet<T>集合中移除与指定谓词所定义的条件相匹配的所有元素 SetEquals     方法         确定HashSet<T>对象与指定的集合中是否包含相同的元素 SynmmetricExceptWith  方法     修改当前的HashSet<T>对象,以仅包含该对象或指定集合中存在的元素 TrimExcess    方法         将HashSet<T>对象的容量设置为它所包含的元素的实际个数,向上舍入为接近的特性与实现的值。 UnionWith     方法         修改当前的HashSet<T>对象,以包含该对象本身和指定集合中存在的所有元素 给个简单的例子,写不完的,总之记得HashSet<T>主要的作用是用来进行,交集、并集等运算的就OK了。 static void Main(string[] args) { HashSet<string> hs = new HashSet<string>(); hs.Add("你"); hs.Add("好"); hs.Add("吗"); HashSet<string> hs1 = new HashSet<string>(); hs1.Add("你"); hs1.Add("好"); bool b = hs1.IsProperSubsetOf(hs); //确定hs1是否是hs的真子集 Console.WriteLine(b); //输出True HashSet<string> hs2 = new HashSet<string>(); hs2.Add("爱你"); IEnumerable<string> list = hs.Union(hs2); //返回并集 foreach (string str in list) { Console.WriteLine(str); //输出 你 好 吗 爱你 } Console.ReadKey(); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值