当前位置: 移动技术网 > IT编程>开发语言>Java > 集合框架--Map

集合框架--Map

2020年07月31日  | 移动技术网IT编程  | 我要评论
Map接口Map接口专门处理键值映射数据的存储,可以根据键实现对值的操作。HashMap是Map最常用的实现类常用方法Map常用方法演示:public class TestMap { public static void main(String[] args) { HashMap map = new HashMap(); map.put("CN", "中华人民共和国"); map.put("UK", "大不列颠联合王国");

Map接口

Map接口专门处理键值映射数据的存储,可以根据键实现对值的操作。HashMap是Map最常用的实现类

常用方法

在这里插入图片描述
Map常用方法演示:

public class TestMap {
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put("CN", "中华人民共和国");
        map.put("UK", "大不列颠联合王国");
        map.put("US", "美利坚合众国");//增
        System.out.println(map.get("CN"));//查
        map.remove("US");
        System.out.println(map.get("US"));
        map.remove("CN", "ABC");//删
        System.out.println(map.get("CN"));
        map.containsKey("key");
        map.containsValue("key");
        map.put("CN", "中国");//改
        System.out.println(map.get("CN"));
        map.replace("CN", "中华人民共和国");
	}
}

Map的遍历

①通过迭代器Iterator实现遍历
②增强型for循环
③键值对

//遍历的方式
Set entry = map.entrySet();
for (Object o : entry) {
	System.out.println(o);
}
//遍历key的方式
Set keys = map.keySet();
Iterator itr=keys.iterator();
while(itr.hasNext()){
	System.out.println(itr.next());
}
//遍历value的方式
Collection values = map.values();
for (Object value : values) {
	System.out.println(value);
}     

泛型

无论是List的get(int index)方法获取元素,还是Map的get(Object key)方法获取元素,还是Iterator的next()方法获取元素,它们获取的都是Object类型,给我们带了不便,未解决此问题,可以使用泛型。
泛型:将对象的类型作为参数,指定到其他类或者方法上,从而保证类型转换的安全性和稳定性。
示例:

ArrayList<String> list = new ArrayList<String>();
// 上述定义后,list只能存放String类型值,其他类型会编译报错
list.add("abc")//正确
list.add(1)// 编译报错

例题
利用map实现:
定义图书类Book,具有属性账号id,书名name、作者author 和价格price,
在创建图书对象时要求通过构造器进行创建,一次性将四个属性全部赋值,
1)要求账户属性是int型,名称是String型,作者是String型,价格是double,
请合理进行封装。
2)在Book类,添加toString方法,要求返回 图书信息字符串,使用\t隔开各信息
3)要求定义一个图书馆Library类,在图书馆类中添加一个集合用于保存多本图书
4)在图书馆类中要求能够新增图书
5)在图书馆类中要求可以查看所有添加过的图书
6)不允许添加重复的图书(如果账号id和书名name相同,则认为两本书是相同的)
(重写equals方法)

// Book类
public class Book  {
    private int id;
    private String name;
    private String author;
    private double price;

    public Book() {
    }

    public Book(int id, String bookName, String author, double price) {
        this.id = id;
        this.name = bookName;
        this.author = author;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return +id+"\t"+name+"\t"+author+"\t"+price;
    }
	// 重写equals()方法
    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if(obj instanceof Book){
            Book book = (Book)obj;
            if(this.id==book.id&&this.name.equals(book.name)){
                return true;
            }
        }
        return false;
    }
	// 重写hashCode()方法
    @Override
    public int hashCode() {
        int result = 17;
        result = result * 31 + this.id;
        result = result * 31 + this.name.hashCode();
        return result;
    }
}
// Library类
public class Library {
    Map<Integer,Book> map = new HashMap();
    public void insertBook(){
        Scanner sc = new Scanner(System.in);
        Integer i = 1;
        do{
            System.out.println("请输入编号:");
            int num = sc.nextInt();
            System.out.println("请输入图书名称:");
            String name = sc.next();
            System.out.println("请输入图书作者:");
            String author = sc.next();
            System.out.println("请输入图书价格:");
            double price = sc.nextDouble();
            Book book = new Book(num,name,author,price);
            map.put(i,book);
            System.out.println("是否继续输入(y/n):");
            String flag2 = sc.next();
            while (!flag2.equals("y")&&!flag2.equals("n")){
                System.out.println("输入有误,请输入(y/n):");
                flag2 = sc.next();
            }
            if(flag2.equals("n")){
                break;
            }
            i++;

        }while(true);
    }
    public void show(){
        System.out.println("图书信息:");

        Iterator iter = map.keySet().iterator();
        while(iter.hasNext()){
            Book book = (Book) map.get(iter.next());
            System.out.println(book);
        }
    }
}
// 测试类
public class TestLibrary {
    public static void main(String[] args) {
        Library library = new Library();
        library.insertBook();
        library.show();
    }
}

Collections的用法

Collections和Collection的区别:

Collections和Collection不同,前者是集合的操作类,后者是集合接口

Collections提供的常用静态方法:

sort():排序
binarySearch():查找
max()\min():查找最大\最小值

public class TestCollection {
    public static void main(String[] args) {
        List list=new ArrayList();
        list.add("abc");
        list.add(123);
        list.add("hello");
        list.add(3.1415926);
        // 匿名内部类 
        Collections.sort(list, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return -1;
            }
        });
        System.out.println(list);
	}
}

本文地址:https://blog.csdn.net/jiandanbuguo/article/details/107677278

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网