Day19 容器2 (集合框架)

Set

Set接口中的实现类
这里写图片描述这里写图片描述
Hash表原理:
这里写图片描述这里写图片描述
总结:
HashSet是如何保证元素的唯一性的呢?

答:是通过元素的两个方法,hashCode和equals方法来完成
如果元素的HashCode值相同,才会判断equals是否为true
如果元素的hashCode值不同,不会调用equals方法

特点:
HashSet底层由哈希表提供支持(一个HashMap的实例)
底层table 顺序表+链表

唯一,无序,允许null元素,但是只能有一个null元素,非同步实现

查询、修改、效率都很高,添加、删除、效率都很高

构造方法
默认存在16个元素
增删改查的成员方法

迭代

hashSet存储自定义对象时,需要重写两个方法,1.hashCode() 2.equals()

LinkedHashSet
有序(添加顺序)
靠另外的链表(双向链表)维护添加的先后顺序
测试代码:

public class TestSet {
    public static void main(String[] args) {
        //HashSet<String> hashSet = new HashSet<>();
//      HashSet<String> hashSet = new LinkedHashSet<>();
//      //添加元素
//      hashSet.add("one");
//      hashSet.add("two");
//      hashSet.add("three");
//      hashSet.add("four");
////        hashSet.add("one");
////        hashSet.add("two");
////        //删除方法
////        hashSet.remove("one");//只能根据值进行删除
//      //没有直接修改方法
//      //1.是否包含
//      System.out.println("是否包含one:"+hashSet.contains("one"));
//      //2.获取索引值  获取最后一个索引值(Set没有类似方法)
//      showHashSet(hashSet);

        //使用HashSet存储自定义对象的时候,需要注意的问题
        Student student1 = new Student("学生1", 18, 80);
        Student student2 = new Student("学生2", 19, 90);
        Student student3 = new Student("学生3", 20, 100);
        Student student4 = new Student("学生4", 23, 99);
        Student student5 = new Student("学生1", 18, 80);
        HashSet<Student> hashSet2 = new HashSet<>();
        hashSet2.add(student1);
        hashSet2.add(student2);
        hashSet2.add(student3);
        hashSet2.add(student4);
        hashSet2.add(student5);
        System.out.println(hashSet2);



    }
    /**
     * 遍历hashSet中所有元素
     * @param hashSet
     */
    public static void showHashSet(HashSet<String> hashSet) {
        //for循环
        for(int i = 0;i < hashSet.size();i++){
            //无法获取i值对应索引值的元素
        }
        //for-each
        for (String string : hashSet) {
            System.out.println(string);
        }
        //迭代器
        Iterator<String> iterator = hashSet.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

}

Comparable 接口

这里写图片描述
在比较自定义类的时候,需要实现这个接口,然后重写compareTo方法,规定按什么方式比较。或者直接使用外部比较器comparator.
有序和无序的区别:
比如arrayList和treeSet,hashSet因为arrayList本身是有序的,是按照索引值排序,所以在插入完元素以后,是按照索引值排序的,要想把插入进去的自定义类元素按自定义规则去比较,就得需要实现这个接口,然后重写compareTo方法,然后调用collections.sort()对arrayList进行排序遍历输出。
而treeSet本身是有序的,输出的时候是按自然顺序升序的,重写comparaTo方法后,无需调用collections.sort(),自己就按升序比较输出。
hashSet本身是无序的,所以任何时候都需要调用collections.sort()去排序。
sort排序
这里写图片描述

TreeSet

TreeSet(TreeMap结构)
Red-Black tree(二叉树)
有序(自然顺序),或者根据Comparator提供的方式进行排序
此实现不是同步的;是否允许null?不允许

TreeSet
构造方法
TreeSet()
构造一个新的空 set,该 set 根据其元素的自然顺序进行排序。
TreeSet(Comparator

public class Student implements Comparable<Student>{
    String name;
    int id;
    double score;
    public Student() {
        super();
    }
    public Student(String name, int id, double score) {
        super();
        this.name = name;
        this.id = id;
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", id=" + id + ", score=" + score + "]";
    }
    @Override
    public int compareTo(Student o) {
        //return this.id - o.id;
        //return o.id-this.id;
        //按分数排
        //return (int)(this.score-o.score);
        Double double1 = this.score;
        Double double2 = o.score;
        //调用Double中重写的方法
        return double1.compareTo(double2);
        //return this.name.compareTo(o.name);

    }

}

外部比较器:

import java.util.Comparator;
/**
 * 外部比较器
 * @author Administrator
 *
 */
public class MyComparatorImpl implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.id - o2.id;
    }

}

测试代码:

public class TestTreeSet {

    public static void main(String[] args) {
        /*TreeSet  treeSet1  = new TreeSet<>();
        treeSet1.add(null);*/
        /*
        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(10);
        treeSet.add(30);
        treeSet.add(20);
        treeSet.add(40);
        treeSet.add(80);
        treeSet.add(10);
        treeSet.add(5);
        System.out.println(treeSet);*/

        //存储自定义对象(一定要实现Comparable接口,指定根据哪个属性进行排序)
        Student student1 = new Student("学生1", 1001, 90);
        Student student2 = new Student("学生2", 1002, 100);
        Student student3 = new Student("学生3", 1003, 70);
        Student student4 = new Student("学生4", 1004, 87);
        Student student5 = new Student("学生5", 1005, 90);
        Student student6 = new Student("学生1", 1001, 90);
        TreeSet<Student> treeSet1 = new TreeSet<>();
        //test2.Student cannot be cast to java.lang.Comparable
        treeSet1.add(student1);
        treeSet1.add(student2);
        treeSet1.add(student3);
        treeSet1.add(student4);
        treeSet1.add(student5);
        treeSet1.add(student6);
        System.out.println(treeSet1+"----------");

        Comparator<Student>comparator = new MyComparatorImpl();
        TreeSet<Student> treeSet2 = new TreeSet<>(comparator);
        treeSet2.add(student1);
        treeSet2.add(student2);
        treeSet2.add(student3);
        treeSet2.add(student4);
        treeSet2.add(student5);
        System.out.println(treeSet2);//根据指定的比较器排序规则进行排序的
        //按名字比较的
        TreeSet<Student> treeSet3 = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.name.compareTo(o2.name);
            }
        });
        treeSet3.add(student1);
        treeSet3.add(student2);
        treeSet3.add(student3);
        treeSet3.add(student4);
        treeSet3.add(student5);
        System.out.println(treeSet3);//根据指定的比较器(匿名内部类)排序规则进行排序的
    }

}

Map

这里写图片描述
这里写图片描述
特点:
键值对形式存在,键唯一,允许,于哈希表的 Map 接口的实现。允许使用null键以及null值(JDK1.2)
*注意,此实现不是同步的。
*元素无序。
与HashMap类似的HashTable ,不允许使用null键以及null值,同步的,其实版本JDK1.0

键:
一般情况下使用Integer或者字符串做为键

键是唯一的,值,(旧值会被新值覆盖)

值:对象

成员方法:
增、
put()
删、
remove(key)
查、
get(key)
contains(key)
contains(value);

put();

LinkedHashMap(有序的<添加顺序>) 靠双向链表进行顺序的维护

TreeMap(有序: 键的自然顺序)
遍历:

//1.keySet()
        System.out.println("---------我是分割线1----------");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println("key="+key+",value="+map.get(key));
        }
        System.out.println("---------我是分割线2----------");
        //2.values()  获取所有的value
        Collection<String>values = map.values();
        for (String value : values) {
            System.out.println(value);
        }
        System.out.println("---------我是分割线3----------");
        //3.entrySet();获取所有的键值对
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            System.out.println("key="+entry.getKey()+",value="+entry.getValue());
        }

增删查改测试代码:

public class TestMap {

    public static void main(String[] args) {
        //HashMap<String, String> hashMap = new HashMap<>();
        //HashMap<String, String> hashMap = new LinkedHashMap<>();
        TreeMap<String, String> hashMap = new TreeMap<>();
        hashMap.put("CN", "China");
        hashMap.put("JP", "Japan");
        hashMap.put("US", "America");
        hashMap.put("US", "USA");
        hashMap.put("CN", "China");
        //删除
        //hashMap.remove("JP");
        //修改
        hashMap.put("US", "asdadf");
        //查询
        String name = hashMap.get("CN");
        boolean isContainKey = hashMap.containsKey("CN");
        boolean isContainValue = hashMap.containsValue("China");
        System.out.println(hashMap.size());
        System.out.println(hashMap);//{CN=China,JP=Japan,US=asdadf}
        showMap(hashMap);
    }
    /**
     * 展示Map中所有元素的方法
     * @param map
     */
    public static void showMap(Map<String, String> map){
        //for循环
        //for-each
        //迭代器
        //1.keySet()
        System.out.println("---------我是分割线1----------");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println("key="+key+",value="+map.get(key));
        }
        System.out.println("---------我是分割线2----------");
        //2.values()  获取所有的value
        Collection<String>values = map.values();
        for (String value : values) {
            System.out.println(value);
        }
        System.out.println("---------我是分割线3----------");
        //3.entrySet();获取所有的键值对
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            System.out.println("key="+entry.getKey()+",value="+entry.getValue());
        }
    }

}

关于map 的排序问题:
1、把要排的属性放到key的位置,会按自然顺序排列
2、如果要想用自定义比较器。要比较哪个属性,把哪个属性放到Key的位置,然后在外部比较器里的泛型加 要比较属性的数据类型
例子:
自定义类:
Student类

public class Student {
    private String name;
    private int age;
    public Student() {
        super();
    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", 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;
    }


}

测试类和外部比较器,用内部类的方式实现:

import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class Test1 {

    public static void main(String[] args) {
        Student student = new Student("张三", 18);
        Student student2= new Student("王五", 13);
        Student student3 = new Student("李四", 15);   
        Student student4 = new Student("李5", 19);
        Student student5 = new Student("李6", 11);
        Student student6 = new Student("李4", 12);

        Map<Integer, Student> map=new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {

                return -(o1-o2);
            }


        });
        map.put(student.getAge(), student);
        map.put(student2.getAge(), student);
        map.put(student3.getAge(), student);
        map.put(student4.getAge(),student);
        map.put(student5.getAge(), student);
        map.put(student6.getAge(), student);

        System.out.println(map);
        Set<Entry<Integer, Student>> entrys=map.entrySet();
        for (Entry<Integer, Student> entry : entrys) {
            System.out.println("key:"+entry.getKey()+"value:"+entry.getValue());
        }


    }

}

注意: 比较年龄大小的时候,应该把外部比较器的泛型加上Interger,而不是Student.

Collections工具类

Collections和Collection不同,前者是集合的操作类,后者是集合接口
Collections提供的静态方法
addAll():批量添加
sort():排序
binarySearch():二分查找
fill():替换
shuffle():随机排序
reverse():逆续
//让非同步的list变成同步的
list = Collections.synchronizedList(list);

 Collections与Collection区别
 * static <T> boolean addAll(Collection<? super T> c, T... elements) 
          将所有指定元素添加到指定 collection 中 
 * 搜索
 * static <T> int  binarySearch(List<? extends Comparable<? super T>> list, T key) 
          使用二分搜索法搜索指定列表,以获得指定对象 
 * 
 * 排序
 * 迭代:
 * static <T> Enumeration<T> enumeration(Collection<T> c) 
          返回一个指定 collection 上的枚举。 
 * static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) 
          使用另一个值替换列表中出现的所有某一指定值。 
static void reverse(List<?> list) 
          反转指定列表中元素的顺序。 


 static void shuffle(List<?> list) 
          使用默认随机源对指定列表进行置换 
 static <T extends Comparable<? super T>> void sort(List<T> list) 
          根据元素的自然顺序 对指定列表按升序进行排序。 
static <T> void  sort(List<T> list, Comparator<? super T> c) 
          根据指定比较器产生的顺序对指定列表进行排序。 
   static void swap(List<?> list, int i, int j) 
          在指定列表的指定位置处交换元素 

static <T> List<T> synchronizedList(List<T> list) 
          返回指定列表支持的同步(线程安全的)列表。 
古老的枚举器Enumeration

在iterator没出现的时候用的都是它。
例如,要输出 Vector v 的所有元素,可使用以下方法:

for (Enumeration e = v.elements(); e.hasMoreElements();)
System.out.println(e.nextElement());这些方法主要通过向量的元素、哈希表的键以及哈希表中的值进行枚举。枚举也用于将输入流指定到 SequenceInputStream 中。

注:此接口的功能与 Iterator 接口的功能是重复的。此外,Iterator 接口添加了一个可选的移除操作,并使用较短的方法名。新的实现应该优先考虑使用 Iterator 接口而不是 Enumeration 接口。

测试代码:

public class Test1 {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "a","bad","cacava");
        System.out.println(list);

        //获取枚举器
        Enumeration<String> enumeration = Collections.enumeration(list);
        while(enumeration.hasMoreElements()){
            System.out.println(enumeration.nextElement());
        }
        //替换
        Collections.replaceAll(list, "a", "****");
        System.out.println(list);
        //反转
        Collections.reverse(list);
        System.out.println(list);
        Collections.shuffle(list);
        System.out.println("打乱之后的:"+list);

        //让非同步的list变成同步的
        list = Collections.synchronizedList(list);
    }

}
面试常见问题
1、集合与数组的比较

数组不是面向对象的,存在明显的缺陷,集合弥补了数组的一些缺点,比数组更灵活更实用,可大大提高软件的开发效率,而且不同的集合框架类可适用不同场合。具体如下:
1:数组能存放基本数据类型和对象,而集合类中只能存放对象。
2:数组容易固定无法动态改变,集合类容量动态改变。
3:数组无法判断其中实际存有多少元素,length只告诉了数组的容量,而集合的size()可以确切知道元素的个数
4:集合有多种实现方式和不同适用场合,不像数组仅采用顺序表方式
5:集合以类的形式存在,具有封装、继承、多态等类的特性,通过简单的方法和属性即可实现各种复杂操作,大大提高了软件的开发效率

2、Collection和Collections的区别

Collection是Java提供的集合接口,存储一组不唯 一,无序的对象。它有两个子接口List和Set。

Java还有一个Collections类,专门用来操作集合类,它提供了一系列的静态方法实现对各种集合的搜索、排序、线程安全化等操作。

3、ArrayList和LinkedList的联系和区别

这里写图片描述

4、Vector和ArrayList的联系和区别

实现原理相同,功能相同,都是长度可变的数组结构,很多时候可以互用
两者的主要区别如下
Vector是早期的JDK接口,ArrayList是替代Vector的新接口
Vector线程安全,ArrayList重速度轻安全,线程非安全
长度需要增长时,Vector默认增长一倍,ArrayList增长50% (1.5+1)

5、HashMap和Hashtable的联系和区别

实现原理相同,功能相同,底层都是哈希表结构,查询速度快,在很多情况下可以互用
两者的主要区别如下
Hashtable是早期的JDK提供的接口,HashMap是新版的JDK提供的接口
Hashtable继承Dictionary类,HashMap实现Map接口
Hashtable是线程安全,HashMap线程非安全
Hashtable不允许null值,HashMap允许null值

6、JDK1.5的新特性有哪些?

泛型
Foreach
自动拆/装箱
枚举
可变参数
静态导入

小结

Set
Map
comparable接口
外部比较器comparator
对自定义类的比较
Collections和Collection的区别
Collections工具类
枚举器
面试常见问题

容器类总结:

这里写图片描述这里写图片描述这里写图片描述
题库链接:
https://www.bbsmax.com/A/QW5YYqGN5m/
集合框架常见题目汇总:
编码题:
1.使用List和Map存放多个图书信息,遍历并输出。其中商品属性:编号,名称,单价,出版社;使用商品编号作为Map中的key。

public class Book
 {
     public int id;
     public String name;
     public double price;
     public String press;
     public Book()
     {
         super();
     }
     public Book(int id, String name, double price, String press)
     {
         super();
         this.id = id;
         this.name = name;
         this.price = price;
         this.press = press;
     }
     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 double getPrice()
     {
         return price;
     }
     public void setPrice(double price)
     {
         this.price = price;
     }
     public String getPress()
     {
         return press;
     }
     public void setPress(String press)
     {
         this.press = press;
     }
     @Override
     public String toString()
     {
         return "Book [id=" + id + ", name=" + name + ", press=" + press
                 + ", price=" + price + "]";
     }
 }
 public class TestListMap
 {
     public static void main(String[] args)
     {
         Book b1 = new Book(1000, "b1", 30.5, "bjsxt");
         Book b1_1 = new Book(1000, "b1", 30, "bjsxt");
         Book b2 = new Book(1000, "b2", 50, "bjsxt");
         Book b3 = new Book(1001, "b3", 30.5, "bjsxt");
         Book b4 = new Book(1002, "b4", 30.5, "bjsxt");
         Book b5 = new Book(1003, "b5", 50, "bjsxt1");
         //使用HashSet存储图书并遍历
         List<Book> bookList = new ArrayList<Book>();
         bookList.add(b1);
         bookList.add(b1);
         bookList.add(b2);
         bookList.add(b3);
         bookList.add(b4);
         bookList.add(b5);
         bookList.add(b1_1);
         System.out.println("遍历输出hashset");
         System.out.println(bookList.size());
         for (Book book : bookList)
         {
             System.out.println(book.toString());
         }
         //使用TreeSet存储图书并遍历
         Map<Integer, Book> bookMap = new HashMap<Integer, Book>();
         bookMap.put(b1.getId(), b1);
         bookMap.put(b1.getId(), b1);
         bookMap.put(b2.getId(), b2);
         bookMap.put(b3.getId(), b3);
         bookMap.put(b4.getId(), b4);
         bookMap.put(b5.getId(), b5);
         bookMap.put(b1_1.getId(), b1_1);
         System.out.println("遍历输出treeset");
         for (Entry<Integer, Book> entry : bookMap.entrySet())
         {
             System.out.println(entry.getKey() + "----------->" + entry.getValue());
         }
     }
 }

2.使用HashSet和TreeSet存储多个商品信息,遍历并输出;其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。
提示:向HashSet中添加自定义类的对象信息,需要重写hashCode和equals( )
向TreeSet中添加自定义类的对象信息,需要实现Comparable接口,指定比较规则

public class Book implements Comparable<Book>
 {
     public int id;
     public String name;
     public double price;
     public String press;
     public Book()
     {
         super();
     }
     public Book(int id, String name, double price, String press)
     {
         super();
         this.id = id;
         this.name = name;
         this.price = price;
         this.press = press;
     }
     public int compareTo(Book o)
     {
         return this.id - o.id;
     }
     @Override
     public int hashCode()
     {
         final int prime = 31;
         int result = 1;
         result = prime * result + id;
         result = prime * result + ((name == null) ? 0 : name.hashCode());
         result = prime * result + ((press == null) ? 0 : press.hashCode());
         long temp;
         temp = Double.doubleToLongBits(price);
         result = prime * result + (int) (temp ^ (temp >>> 32));
         return result;
     }
     @Override
     public boolean equals(Object obj)
     {
         if (this == obj)
         {
             return true;
         }
         if (obj == null)
         {
             return false;
         }
         if (getClass() != obj.getClass())
         {
             return false;
         }
         Book other = (Book) obj;
         if (id != other.id)
         {
             return false;
         }
         if (name == null)
         {
             if (other.name != null)
             {
                 return false;
             }
         } else if (!name.equals(other.name))
         {
             return false;
         }
         if (press == null)
         {
             if (other.press != null)
             {
                 return false;
             }
         } else if (!press.equals(other.press))
         {
             return false;
         }
         if (Double.doubleToLongBits(price) != Double
                 .doubleToLongBits(other.price))
         {
             return false;
         }
         return true;
     }
     @Override
     public String toString()
     {
         return "Book [id=" + id + ", name=" + name + ", press=" + press
                 + ", price=" + price + "]";
     }
 }
 public class TestSet
 {
     public static void main(String[] args)
     {
         Book b1 = new Book(1000, "b1", 30.5, "bjsxt");
         Book b1_1 = new Book(1000, "b1", 30, "bjsxt");
         Book b2 = new Book(1000, "b2", 50, "bjsxt");
         Book b3 = new Book(1001, "b3", 30.5, "bjsxt");
         Book b4 = new Book(1002, "b4", 30.5, "bjsxt");
         Book b5 = new Book(1003, "b5", 50, "bjsxt1");
         //使用HashSet存储图书并遍历
         Set<Book> hashSet = new HashSet<Book>();
         hashSet.add(b1);
         hashSet.add(b1);
         hashSet.add(b2);
         hashSet.add(b3);
         hashSet.add(b4);
         hashSet.add(b5);
         hashSet.add(b1_1);
         System.out.println("遍历输出hashset");
         System.out.println(hashSet.size());
         for (Book book : hashSet)
         {
             System.out.println(book.toString());
         }
         //使用TreeSet存储图书并遍历
         Set<Book> treeSet = new TreeSet<Book>();
         treeSet.add(b1);
         treeSet.add(b1);
         treeSet.add(b2);
         treeSet.add(b3);
         treeSet.add(b4);
         treeSet.add(b5);
         treeSet.add(b1_1);
         System.out.println("遍历输出treeset");
         for (Book book : treeSet)
         {
             System.out.println(book.toString());
         }
     }
 }

3.实现List和Map数据的转换。具体要求如下:
功能1:定义方法public void listToMap( ){ }将List中Student元素封装到Map中
1) 使用构造方法Student(int id,String name,int age,String sex )创建多个学生信息并加入List
2) 遍历List,输出每个Student信息
3) 将List中数据放入Map,使用Student的id属性作为key,使用Student对象信息作为value
4) 遍历Map,输出每个Entry的key和value
功能2:定义方法public void mapToList( ){ }将Map中Student映射信息封装到List
1) 创建实体类StudentEntry,可以存储Map中每个Entry的信息
2) 使用构造方法Student(int id,String name,int age,String sex )创建多个学生信息,并使用Student的id属性作为key,存入Map
3) 创建List对象,每个元素类型是StudentEntry
4) 将Map中每个Entry信息放入List对象

public class TestListToMap
 {
     public void listToMap()
     {
         //1.创建多个学生信息
         Student stu1 = new Student(110, "小明", 23, 98.0);
         Student stu2 = new Student(111, "大刚", 21, 80.5);
         Student stu3 = new Student(112, "小白", 12, 93.0);
         //2.加入List
         List<Student> list = new ArrayList<Student>();
         list.add(stu1);
         list.add(stu2);
         list.add(stu3);
         //3.遍历List,输出每个Student信息
         for (Student stu : list)
         {
             System.out.println(stu);
         }
         //4.将List中数据放入Map,使用Student的id属性作为key                                         Map<Integer, Student> map = new HashMap<Integer, Student>();
         Iterator<Student> it = list.iterator();
         while (it.hasNext())
         {
             Student stu = it.next();
             map.put(stu.getId(), stu);
         }
         //5.遍历Map,输出每个Entry的key和value
         Set<Entry<Integer, Student>> entrySet = map.entrySet();
         for (Entry<Integer, Student> entry : entrySet)
         {
             System.out.println(entry.getKey() + "---->" + entry.getValue());
         }
     }
 }
 public class StudentEntry
 {
     private int key;//关键字
     private Student stu;//学生
     public int getKey()
     {
         return key;
     }
     public void setKey(int key)
     {
         this.key = key;
     }
     public Student getStu()
     {
         return stu;
     }
     public void setStu(Student stu)
     {
         this.stu = stu;
     }
 }
 public class TestMapToList
 {
     public void mapToList()
     {
         //1.创建多个学生信息
         Student stu1 = new Student(110, "小明", 23, 98.0);
         Student stu2 = new Student(111, "大刚", 21, 80.5);
         Student stu3 = new Student(112, "小白", 12, 93.0);
         //2.使用Student的id属性作为key,存入Map
         Map<Integer, Student> map = new HashMap<Integer, Student>();
         map.put(stu1.getId(), stu1);
         map.put(stu2.getId(), stu2);
         map.put(stu2.getId(), stu3);
         //3.创建List对象,每个元素类型是StudentEntry
         List<StudentEntry> list = new ArrayList<StudentEntry>();
         //4.将Map对象转化为List集合
         for (Entry<Integer, Student> entry : map.entrySet())
         {
             StudentEntry studentEntry = new StudentEntry();
             // 将map中的一个映射关系,封装为一个studentEntry对象
             studentEntry.setKey(entry.getKey());
             studentEntry.setStu(entry.getValue());
             // 将studentEntry对象List集合
             list.add(studentEntry);
         }
         //5.遍历Map
         for (StudentEntry se : list)
         {
             System.out.println(se.getKey() + "\t" + se.getStu());
         }
     }
 } 

4.假如有以下email数据“aa@sohu.com,bb@163.com,cc@sina.com,..”现需要把email中的用户部分和邮件地址部分分离,分离后以键值对应的方式放入HashMap?

public class EmailSplit
 {
     public static void main(String[] args)
     {
         String str = "aa@sohu.com,bb@163.com,cc@sina.com";
         //得到每一个email
         String strs[] = str.split(",");
         //存放分离后email的信息
         Map<String, String> emailMap = new HashMap<String, String>();
         for (String email : strs)
         {
             String temp[] = email.split("@");
             //分割email存入map
             emailMap.put(temp[0], temp[1]);
         }
         System.out.println(emailMap.toString());
     }
 }

写法2:

public class Test1 {

    public static void main(String[] args) {

        String str = "aa@sohu.com,bb@163.com,cc@sina.com";
        String[] arr = str.split(",");
        String front;
        String end;
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            front = arr[i].substring(0, str.indexOf("@"));
            end = arr[i].substring(str.indexOf("@"), arr[i].length());
            map.put(front, end);
        }
        show(map);

    }

    public static void show(Map<String, String> map) {
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Entry<String, String> entry : entrys) {
            System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());

        }
    }
}

5.用代码写出遍历List的三种方式。


public class Test1 {

    public static void main(String[] args) {
            List<String>  list=new ArrayList<>();
            list.add("java");
            list.add("C#");
            show(list);


    }
    public static void show(List<String>list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        for (String string : list) {
            System.out.println(string);
        }
        Iterator<String>  iterator=list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

}

6.用代码写出遍历Set的两种方式。


public class Test1 {
   public static void main(String[] args) {
    Set<String>  set=new HashSet<>();
    set.add("java");
    set.add("html");
    set.add("css");
    show(set);


}
   public static void show(Set<String> set  ) {
    for (String string : set) {
        System.out.println(string);
    }

    Iterator<String>  iterator=set.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}
}

7.用代码写出遍历map的方式。


public class Test1 {

    public static void main(String[] args) {
            Map<String, String>  map=new HashMap<>();
            map.put("CN", "china");
            map.put("US", "America");
            map.put("JP", "japan");
            show(map);

    }
    public static void show(Map<String, String>map) {
        //获取所有的键值对
        Set<Map.Entry<String, String>> entrys=map.entrySet();
        for (Entry<String, String> entry : entrys) {
            System.out.println("key:"+entry.getKey()+" value:"+entry.getValue());
        }
        //获取所有的key
        Set<String> keys=map.keySet();
        for (String key : keys) {
            System.out.println("key:"+key+" value:"+map.get(key));
        }
        //获取所有的value
        Collection<String> values=map.values();
        for (String value : values) {
            System.out.println("value:"+value);
        }

    }

}

编写时出现的问题和用到的知识:
question1:
注意List有两个,一般用的是java.util包里的 ,要是同时用两个,另一个要有完整路径。
1、Map的遍历方式.和其他容器接口不一样
2、如果有自定义类,泛型应该是自定义类型,
3、要求输出自定义类型的时候要有重写toString方法。
question2:
1、HashSet唯一性: 不可以添加相同的对象,但是对象不同,内容相同,也可以添加进去。
2、注意用迭代器遍历的时候的参数类型。遍历与直接打印的区别,直接打印的时候不能加换行,遍历加了换行。
3、注意定义比较规则的时候要实现comparable接口,重写compareTo方法,里面用compareTo比较
question3:
1、把List转换成map 通过List迭代器把List元素转换成Map
2、map的遍历方式entry
3、arrayList里的东西的比较,1、实现comparable接口,重写compareTo方法,里面用compareTo比较,然后调用collections.sort(list);排序,2、用自定义比较器comparator.
在自定义类比较的时候,无序的时候可以不调用collections.sort方法,有序的时候必须调用。
question4:question:将邮箱用户名和@后面的信息分离 str.split();substring();
question5:用代码写出遍历List的三种方式。
question6:用代码写出遍历Set的两种方式。
question7:用代码写出遍历map的方式。 3种方式

总结:
1、ArrayList 允许添加空元素
2、ArrayList 在创建的时候size为0,在add()方法后,自动扩容10,每次扩容50%.
ArrayList 和 LinkedList 都是List 元素有序,不唯一,有序指的是索引顺序,而不是大小顺序。
3、LinkedList 允许添加空元素, 可以当栈(有限制的双端队列), 队列queue,双端队列deque来使用.
4、利用LinkedList 创建一个栈Deque stack = new LinkedList();
栈是一种有限制的双端队列
push 入栈, pop出栈, 获取栈顶元素 peek
5、利用LinedList 创建一个队列Queue queue = new LinkedList();
6、LinkedList同时是Deque和Queue的实现类,所以在Java中完成对栈和队列的操作,
* 使用LinkedList即可,底层结构是链表;
* 如果希望底层结构使用数组,请使用ArrayDeque
* 如果希望保证并发情况下线程安全,可以使用LinkedBlockingDeque
7、在HashSet里添加自定义元素 必须实现HashCode、equals方法。
在jdk1.8后,如果Hashset 后面的链表数>=7,就会变成顺序表+散列表+红黑树,也就是变成了Tree结构,也要
实现Comparable接口
8、在treeSet里添加自定义元素 因为红黑树的结构问题,必须实现Comparable接口,重写compareTo方法 ,以让他们比较才能添加进去。
存储自定义对象(一定要实现Comparable接口,指定根据哪个属性进行排序),或者使用外部比较器。
import java.util.Comparator;

import com.bjsxt.container.entity.Student;
/**
* 按照分数升序排列
* @author Administrator
*
*/
public class StudentScoreCompartor implements Comparator{

@Override
public int compare(Student stu1, Student stu2) {
    double score1 = stu1.getScore();
    double score2 = stu2.getScore();
    if(score1 > score2){
        return 1;
    }else if(score1 < score2){
        return -1;
    }else{
        return 0;
    }
}

}
9、map不能用迭代器 Interator, entrySet是Set,可以用迭代器或者for-each。
遍历map。先转换成Set,在遍历。
10、map里,如果值重复,用新值替代旧值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值