栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Collection集合

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Collection集合

1.

 

//创建集合对象

Collection c = new ArrayList();

2.Collection集合的常用方法

 

 Alt + 7: 打开类的所有窗口,能够看到所有信息

Collection c = new ArrayList();



//boolean add(E e);添加元素

c.add("hello");




//boolean remove(Object o);从集合中移除指定元素

c.remove("hello");



//void clean();     清空集合中的元素

c.clean();




//bolean contains(Object o);    判断集合中是否存在指定的元素

c.contains("world");





//int size();    集合的长度,集合中元素个数

c.size();




//boolean isEmpty();    判断集合是否为空

c.isEmpty();
(5)Coleantion集合的遍历

 

(6)集合的使用步骤

 案例:Collection集合存储学生对象并遍历 

package Collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CollectionDemo {
    public static void main(String[] args) {
        //创建集合对象
        Collection c = new ArrayList();

        //创建学生对象
        Student s1 = new Student("彭于晏",18);
        Student s2 = new Student("李易峰",16);
        Student s3 = new Student("白敬亭",17);

        //把学生对象添加到集合
        c.add(s1);
        c.add(s2);
        c.add(s3);

        //遍历集合(迭代器方法)
        Iterator it = c.iterator();
        while(it.hasNext()){
           Student s =  it.next();
            System.out.println(s.getName() + ", " + s.getAge());
        }
    }
}






public class Student {
//成员变量
    private String name;
    private int age;
    //构造方法
    public Student() {
    }

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


    //成员方法:get/set方法

    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;
    }
}

2.List(需要导包) (1)概述和特点

 (2)List集合的特有方法

 List集合带索引,不能越界


//创建集合对象
List list = new ArrayList();

//添加元素
list.add("hello");
list.add("world");
list.add("java");


//for循环遍历List集合
for(int i = 0; i 
 案例:List集合存储学生对象并遍历 

package List;
//导包
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class ListDemo {
    public static void main(String[] args) {
        //创建List集合对象
        List list = new ArrayList();        //需要Array、List导包、List导包

        //创建学生对象
        Student s1 = new Student("彭于晏",18);
        Student s2 = new Student("李易峰",16);
        Student s3 = new Student("白敬亭",17);

        //把学生添加到集合
        list.add(s1);
        list.add(s2);
        list.add(s3);
        //遍历集合(迭代器/for循环)
        
        //for循环
        for(int i=0; i it = list.iterator();        //需要Iterator导包
        while(it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + ", " + s.getAge());
        }

    }
}









public class Student {
    //定义成员变量
    private String name;
    private int age;

    //构造方法
    public Student() {
    }

    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;
    }

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


        //成员方法:get/set

    }
}
(3)并发修改异常 P229

 (4)Listlterator 列表迭代器

 

 (5)增强for循环(简化数组和Collection集合的遍历)


//数组
int[] arr = {1,2,3,4,5};

for(int i: arr){
    System.out.println(i);
}



//数组
String[] strArray = {"hello","world","java"};
for(String s : strArray){
    Systeem.out.println(s);

}



//集合
List list = new ArrayList();
list.add("hello");
list.add("world");
list.add("java");
for(String s : list){
    System.out.println(s);
}

案例:List集合存储学生对象用3种方式遍历

package List2;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {
        //创建List集合对象
        List list = new ArrayList();
        //创建学生对象
        Student s1 = new Student("彭于晏",18);
        Student s2 = new Student("李易峰",16);
        Student s3 = new Student("白敬亭",17);
        //把学生添加到集合
        list.add(s1);
        list.add(s2);
        list.add(s3);

        //遍历集合
        //①Iterator迭代器
        Iterator it = list.iterator();
        while(it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + ", " + s.getAge());

        }
        System.out.println("-------------------");

        //②普通for循环;带有索引
        for(int i=0; i 

(6)数据结构

计算机存储、组织数据的方式;相互之间存在一种或多种特定关系的数据元素的集合

(7)数据结构:栈

压栈/进栈:

压栈/弹栈:栈顶元素先出去

(8)数据结构:队列

 (9)数据结构:数组

 

 (10)数据结构:链表

 

 (11)List集合子类特点

List集合子类特点:ArrayList、linkedList

 

  

 案例:ArrayList集合存储学生对象用3种方式遍历

package ArrayList;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListDemo {
    public static void main(String[] args) {
        //创建ArrayList集合对象
        ArrayList array = new ArrayList();

        //创建学生对象
        Student s1 = new Student("s1",12);
        Student s2 = new Student("s2",13);
        Student s3 = new Student("s3",14);
        //把学生添加到集合
        array.add(s1);
        array.add(s2);
        array.add(s3);

        //集合遍历
        //①迭代器:集合特有的遍历方式
        Iterator it = array.iterator();
        while(it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + ", " + s.getAge());
        }
        System.out.println("-------------------------------");

        //②普通for循环:带有索引的遍历方式
        for(int i=0; i
(12)linkedList集合的特有功能

3 .Set集合 (1)概述和特点

 HashSet对集合的迭代顺序不做任何保证

(2)哈希值 

 (3)HashSet集合概述和特点

 

 (4)HashSet集合保证元素唯一性源码分析

 (5)常见数据结构之哈希表

先比较哈希值,哈希值相同再比较内容,如果内容也相同证明重复,不存入 

 

(6)linkedHashSet集合概述和特点

 

 (7)TreeSet集合概述和特点

 

//创建集合对象
TreeSet ts = new TreeSet();

//所有基本类型存储时,用的都是对应的包装类型,如;int ---Integer
 (8)自然排序Comparable的使用         P246(再补充)

 让类实现该接口,类可以让这个类的对象进行自然排序

package TreeSet;

public class Student implements Comparable{
    //成员变量
    private String name;
    private int age;
    //构造方法
    public Student() {
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    //成员方法:get/set方法
    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 int compareTo(Student s){
        //return 0;       //认为s1,s2,s3,s4是重复元素,不会存储
        //return 1;           //按照升序来存储
        //return -1;        //按照降序来存储

        //按照年龄从小到大排序(this 放在前面)
        int num = this.age - s.age;


        //年龄按照降序排列(this 放在后面)
        //int num = s.age - this.age;
       // return num;

        //年龄相同时,按照姓名的字母顺序排序
        int num2 = num==0?this.name.compareTo(s.name):num;
        return num2;
    }
}






import java.util.TreeSet;

public class TreeSetDemo02 {
    public static void main(String[] args) {


        //创建集合对象
        TreeSet ts = new TreeSet();


        //创建学生对象
        Student s1 = new Student("d1",11);
        Student s2 = new Student("c2",12);
        Student s3 = new Student("b3",13);
        Student s4 = new Student("a4",14);

        //把学生添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        //遍历集合
        for(Student s : ts){
            System.out.println(s.getName() + ", " + s.getAge());
        }
    }
}


(9)比较器排序Comparator的使用

3.Set  案例:成绩排序

package TreeSet2;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        //创建TreeSet集合对象,通过比较器进行排序
        TreeSet ts = new TreeSet(new Comparator(){    //接收比较器接口对象,用匿名内部类实现
            @Override
            public int compare(Student s1,Student s2){
                //int num = (s1.getChinese() + s1.getMath()) - (s2.getChinese() + s2.getMath());
                //主要条件
                int num = s2.getSum() - s1.getSum();    //比较总分:从高到低(从高到低:s2 - s1; 从低到高:s1 - s2)
                //次要条件:2个(比较语文成绩,姓名)
                int num2 = num==0 ? s1.getChinese() - s2.getChinese() : num;    //总分相同的情况下,比较语文成绩
                int num3 = num2==0 ? s1.getName().compareTo(s2.getName()) : num2;   //语文成绩相同的情况下,比较姓名(用compareTo方法)
                return num3;


            }
        });



        //创建学生对象
        Student s1 = new Student("彭于晏",98,100);
        Student s2 = new Student("李易峰",95,95);
        Student s3 = new Student("白敬亭",100,93);
        Student s4 = new Student("潘丢丢",100,97);
        Student s5 = new Student("不知道",98,98);
        Student s6 = new Student("刘以豪",97,99);
        Student s7 = new Student("褚克桓",97,99);

        //把学生对象添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        ts.add(s7);

         //遍历集合:增强for
        for(Student s :ts){
            System.out.println(s.getName() +  ", " + s.getChinese() + " ," + s.getMath() + ", " + s.getSum());
        }

    }
}










//定义学生类
public class Student {
    //定义成员变量
    private String name;
    private int chinese;
    private int math;


    //构造方法
    public Student() {
    }

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

    //成员方法:get/set方法

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public String getName() {
        return name;
    }

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

    //
    public int getSum(){
        int num = getChinese() + getMath();
        return num;
    }

}

案例:不重复的随机数

import java.util.*;

public class SetDemo {
    public static void main(String[] args) {
        //创建Set集合
        Set set = new HashSet();  //无序排列
        //set set = new TreeSet();    //有序排列

        //创建随机数对象
        Random r = new Random();

        //判断集合的长度是不是小于10
        while(set.size()<10){
            int number = r.nextInt(20) + 1; //生成随机数:1~20
            set.add(number);    //保证没有添加重复元素

        }
        //遍历集合
        for(Integer i : set){
            System.out.println(i);
        }

    }


}
4.泛型 (1)概述

 (2)泛型类
//泛型类

public class Deneric{

    
    
    //生成get/set方法
    
}

(3)泛型方法

public class Generic{

    public  void show(T t){    //泛型方法
        //方法体
    }

}

(4)泛型接口
//泛型接口

//格式:修饰符 interface 接口名<类型>{ }

public interface Generic{ }

(5)类型通配符

 

//类型通配符上限:     表示本类或者其子类型


List list1 = new ArrayLIst;



//类型通配符下限:     表示本类或者其父类型


List list1 = new ArrayLIst;
 

(6)可变参数

 

 包含多个参数,可变参数放在后面

 (7)可变参数的使用





 5.Map (1)Map集合的概述和使用

 

 HashMap保证了键的唯一性

(2)Map集合的基本功能

//创建集合对象

    Map map = new HashMap();

 (3) Map集合的获取功能

 

(4)Map集合的遍历(方式1)

 (5)Map集合的遍历(方式2)

 案例:HashMap 集合存储学生对象并遍历

package HashMap;

import java.util.HashMap;

import java.util.Map;
import java.util.Set;

public class HashMapDemo {
    public static void main(String[] args) {
        //创建HashMap集合对象
        HashMap hm = new HashMap();

        //创建学生对象
        Student s1 = new Student("彭于晏", 18);
        Student s2 = new Student("李易峰", 16);
        Student s3 = new Student("褚克桓", 17);

        //把学生添加到集合
        hm.put("001", s1);
        hm.put("002", s2);
        hm.put("003", s3);

        //方式1:
        Set keySet = hm.keySet();
        for (String key : keySet) {
            Student value = hm.get(key);
            System.out.println(key + ", " + value.getName() + ", " + value.getAge());
        }
        System.out.println("---------------------");

        //方式2:
        Set> entrySet = hm.entrySet();
        for (Map.Entry me : entrySet) {
            String key = me.getKey();
            Student value = me.getValue();
            System.out.println(key + ", " + value.getName() + ", " + value.getAge());
        }
    }
}









//定义学生类
public class Student {

    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        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;
    }
}
 案例:HashMap集合存储学生对象并遍历

 案例:ArrayList集合存储HashMap元素并遍历

package HashMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class HashMapDemo3 {
    public static void main(String[] args) {
        //创建ArrayList集合
        ArrayList> array = new ArrayList>();

        //创建HashMap集合,并添加键值对元素
        HashMap hm1 = new HashMap();
        hm1.put("孙策","大乔");
        hm1.put("周瑜","小乔");
        //把HashMap作为元素添加到ArrayList集合
        array.add(hm1);

        HashMap hm2 = new HashMap();
        hm2.put("郭靖","黄蓉");
        hm2.put("杨过","小龙女");
        //把HashMap作为元素添加到ArrayList集合
        array.add(hm2);

        HashMap hm3 = new HashMap();
        hm3.put("令狐冲","任盈盈");
        hm3.put("林平之","岳灵珊");
        //把HashMap作为元素添加到ArrayList集合
        array.add(hm3);

        //遍历ArrayList集合
        for(HashMap hm : array){     //每个hm就是ArrayList中的每个元素
            Set keySet = hm.keySet();
            for(String key : keySet){
                String value = hm.get(key);
                System.out.println(key + ", " + value);
            }
        }
    }
}
案例:Hashmap集合存储ArrayList元素并遍历

package HashMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class HashMapDemo4 {
    public static void main(String[] args) {
        //创建HashMap集合存储ArrayList对象
        HashMap> hm = new HashMap>();

        //创建ArrayList集合,并添加元素
        //三国演义
        ArrayList sgyy = new ArrayList();
        sgyy.add("诸葛亮");
        sgyy.add("赵云");
        //把arrayList作为元素添加到HashMap集合
        hm.put("三国演义",sgyy);

        //西游记
        ArrayList xyj = new ArrayList();
        xyj.add("唐僧");
        xyj.add("孙悟空");
        //把arrayList作为元素添加到HashMap集合
        hm.put("西游记",xyj);


        //水浒传
        ArrayList shz = new ArrayList();
        shz.add("武松");
        shz.add("鲁智深");
        //把arrayList作为元素添加到HashMap集合
        hm.put("水浒传",shz);

        //遍历HashMap集合
        Set keySet = hm.keySet();
        for(String key : keySet){
            System.out.println(key);
            ArrayList value = hm.get(key);
            for(String s : value){
                System.out.println("t" + s);
            }
        }

    }
}
案例:统计字符串中每个字符出现的次数

package HashMap;

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;


public class HashMapDemo5 {
    public static void main(String[] args) {
        
        //创建Scanner 对象
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String line = input.nextLine();
        //创建HashMap集合,键是Character,值是Integer
        //HashMap hm = new HashMap();     //HashMap 无序
        TreeMap hm = new TreeMap();       //TreeSet 有序
        //遍历字符串,得到每一个字符
        for(int i=0; i keySet = hm.keySet();
        for(Character key : keySet){
            Integer value = hm.get(key);
            sb.append(key).append("(").append(value).append(")");
        }
        String result = sb.toString();
        //输出结果
        System.out.println(result);
    }
}
6.  Collections (1)概述和使用 

 

//创建集合对象
List list = new ArrayList();


//添加元素
list.add(30);
list.add(20);
list.add(50);
list.add(10);
list.add(40);


//升序
    Collections.sort(list);


//反转
    Collections.reserve(list);


//随机排序
    Collections.shuffle(list);
 ArrayList存储学生对象并排序

package Collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import static java.util.Collections.sort;

public class CollectionsDemo {
    public static void main(String[] args) {
        //创建ArrayList集合对象
        ArrayList array = new ArrayList();
        //创建学生对象
        Student s1 = new Student("pengyuyan",30);
        Student s2 = new Student("chukehuan",18);
        Student s3 = new Student("liyifeng",19);
        Student s4 = new Student("liuyihao",17);

        //把学生对象添加到集合
        array.add(s1);
        array.add(s2);
        array.add(s3);
        array.add(s4);
        //使用Collections对ArrayList集合排序
        Collections.sort(array,new Comparator() {
            @Override
            public int compare(Student s1,Student s2){
                //按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                        return num2;
            }
        });

        //遍历集合
        for(Student s : array){
            System.out.println(s.getName() + ", " + s.getAge());
        }
    }
}
案例:模拟斗地主

 

package Collections;

import java.util.ArrayList;
import java.util.Collections;

import static java.util.Collections.shuffle;


public class PokerDemo {
    public static void main(String[] args) {
        //1.创建一个牌盒,也就是定义一个集合对象,用ArrayList集合实现
        ArrayList array = new ArrayList();

        //往牌盒里面装牌
        
        //定义花色数组 colors
        String[] colors = {"♦","♣","❤","♠"};
        //定义点数数组 numbers
        String[] numbers = {"1","2","3","4","5","6","7","8","9","10","J","Q","K","A"};
        //花色和点数拼接(数组array)
        for(String color : colors){
            for(String number : numbers){
                array.add(color+number);
            }
        }
        array.add("大王");
        array.add("小王");

        //3.洗牌,也就是把牌打散,用Collections的shuffle()方法实现
        Collections.shuffle(array);

        //4.发牌,也就是遍历集合,给三个玩家发牌(3个集合)
        ArrayList array1 = new ArrayList();
        ArrayList array2 = new ArrayList();
        ArrayList array3 = new ArrayList();
        ArrayList array4 = new ArrayList();

        for(int i=0; i< array.size(); i++){
            //得到牌
            String poker = array.get(i);
            if(i  >= array.size() - 3){
                array4.add(poker);
            }else if(i % 3 == 0){
                array1.add(poker);
            }else if(i % 3 == 1){
                array2.add(poker);
            }
            else if(i % 3 == 2){
                array3.add(poker);
            }
        }
        //看牌(调用方法)
        lookPoker("array1",array1);
        lookPoker("array2",array2);
        lookPoker("array3",array3);
        lookPoker("array4",array4);

        System.out.println(array);
    }


    //看牌的方法
    public static void lookPoker(String name,ArrayList array){
        System.out.print(name + "的牌是:");
        for(String poker : array){
            System.out.print(poker + " ");
        }
        System.out.println();       //显示完每个人的牌之后换行
    }
}
案例:模拟斗地主升级版

 

package Collections;

import java.util.*;

import static java.util.Collections.shuffle;


public class PokerDemo2 {
    public static void main(String[] args) {
        //1.创建HashMap,键是编号Integer,值是牌String
        HashMap hm = new HashMap();

        //2.创建ArrayList,存储编号
        ArrayList array = new ArrayList();

        //3.创建花色数组和点数数组
        
        //创建花色数组colors
        String[] colors = {"♦", "♣", "❤", "♠"};
        //创建点数数组numbers
        String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};


        //4.从0开始往HashMap里面存储编号,并存储对应的牌,同时往ArrayList里面存储编号
        //拼接花色和点数数组
        int index = 0;
        for (String color : colors) {
            for (String number : numbers) {
                hm.put(index, color + number);
                array.add(index);
                index++;
            }
        }
        hm.put(index, "大王");
        array.add(index);
        index++;
        hm.put(index, "小王");
        array.add(index);


        //5.洗牌(洗的是编号),用Collection的Shuffle()方法实现
        Collections.shuffle(array);

        //6.发牌(发的是编号,为保证编号是排序的,创建TreeSet集合接收)
        TreeSet pyySet = new TreeSet();     //彭于晏
        TreeSet ckhSet = new TreeSet();     //褚克桓
        TreeSet lyfSet = new TreeSet();     //李易峰
        TreeSet lyhSet = new TreeSet();     //刘以豪(底牌)
        for (int i = 0; i < array.size(); i++) {
            int x = array.get(i);
            if (i >= array.size() - 3) {
                lyhSet.add(x);
            } else if (i % 3 == 0) {
                pyySet.add(x);
            } else if (i % 3 == 1) {
                ckhSet.add(x);
            } else if (i % 3 == 2) {
                lyfSet.add(x);
            }
        }

        //8.调用看牌方法
        lookPoker("彭于晏",pyySet,hm);
        lookPoker("褚克桓",ckhSet,hm);
        lookPoker("李易峰",lyfSet,hm);
        lookPoker("刘以豪",lyhSet,hm);

    }
    // 7.定义方法看牌(遍历TreeSet集合,获取编号,到HashSet集合找对应的牌)
    public static void lookPoker(String name, TreeSet ts, HashMap hm){
        System.out.print(name + "的牌是:");
        for(Integer key : ts){
            String poker = hm.get(key);
            System.out.print(poker+ " ");
        }
        System.out.println();
    }

}

 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号