代码1:
package com.atguigu.day15; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; /* 集合:存储多个数据的,长度不固定 数组:数组的长度是固定的 Collection List:有序,按照添加的顺序,不唯一,可以添加重复的元素 ArraysList LinkedList Set:无序,不是按照添加的顺序输出,唯一,不可以添加重复元素 HashSet LinkedHashSet TreeSet * */ public class Demo10 { @Test public void test1(){ //多态 Collection col1 = new ArrayList(); //添加元素 col1.add(10);//内部Integer.valueof(10) col1.add(20); col1.add(new Date()); System.out.println(col1);//[10, 20, Fri Jan 07 11:02:11 CST 2022] Collection col2 = new ArrayList(); col2.add("张无忌"); col2.add("赵敏"); //add()会将一个集合作为一个元素处理 col1.add(col2); System.out.println(col1); //[10, 20, Fri Jan 07 11:08:01 CST 2022, [张无忌, 赵敏]] //addAll()会将集合中的每一个元素进行单独处理 col1.addAll(col2); System.out.println(col1); //[10, 20, Fri Jan 07 11:08:01 CST 2022, [张无忌, 赵敏], 张无忌, 赵敏] System.out.println(col1.size());//长度为6 //判断元素是否在集合内 boolean isExsit = col2.contains("张无忌"); System.out.println(isExsit);//true //清除指定元素 col1.remove(10); System.out.println(col1);//[20, Fri Jan 07 11:15:26 CST 2022, [张无忌, 赵敏], 张无忌, 赵敏] //删除集合 col1.removeAll(col2); System.out.println(col1);//[20, Fri Jan 07 11:15:26 CST 2022, [张无忌, 赵敏]] Collection col3 = new ArrayList(); col3.add(10); col3.add(20); col3.add(30); Collection col4 = new ArrayList(); col4.add(10); col4.add(20); col3.retainAll(col4); System.out.println(col3);//[10, 20] //判断集合是否为空 System.out.println("col3.isEmpty() = " + col3.isEmpty());//col3.isEmpty() = false //清除集合所有元素 col3.clear(); System.out.println(col3);//[] } @Test public void test2(){ Collection col1 = new ArrayList(); col1.add(10); col1.add(20); col1.add(30); col1.add("张无忌"); //遍历集合第一种方法 for (Object ojb:col1){ System.out.println(ojb); } //遍历集合第二种方法,通过创建迭代器实现 //hasNext()判断游标后面是否还有数据 //next()拿到指定的数据 Iterator iterator = col1.iterator(); while (iterator.hasNext()){ Object obj=iterator.next(); System.out.println(obj); } //转换类型 Collection col2 = new ArrayList(); col2.add("abc"); col2.add("efg"); col2.add("bpf"); for (Object obj:col2){ String s = (String)obj; System.out.println(s); } System.out.println("-------------------"); //泛型:规定你输入数据的类型 Collection<引用数据类型> Collection<String> col3 = new ArrayList<>(); col3.add("司马亮"); col3.add("司马玮"); col3.add("司马伦"); col3.add("司马囧"); for (String s:col3){ if (s.equals("司马伦")){ // col3.add("司马乂");//此时会报错,java.util.ConcurrentModificationException } } System.out.println(col3); System.out.println("-------------------"); Iterator<String> iterator1 = col3.iterator(); while (iterator1.hasNext()){ String s = iterator1.next(); if (s.equals("司马伦")){ // col3.add("司马乂");//此时会报错,java.util.ConcurrentModificationException iterator1.remove(); } } System.out.println(col3); /*modcount:记录集合的操作次数 在进行集合遍历的时候,不要使用集合对象直接新增或者删除元素,应该使用iterator去操作 */ } }
代码2:
package com.atguigu.day15; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Demo11 { public static void main(String[] args) { Collection<StudentTest> colTest = new ArrayList<>(); StudentTest stu1 = new StudentTest("陆小凤",98); StudentTest stu2 = new StudentTest("西门吹雪",38); StudentTest stu3 = new StudentTest("摘星子",58); colTest.add(stu1); colTest.add(stu2); colTest.add(stu3); Iterator<StudentTest> iterator = colTest.iterator(); while (iterator.hasNext()){ StudentTest stu = iterator.next(); if (stu.score<60){ iterator.remove(); } } System.out.println(colTest); } } class StudentTest{ String name; int score; public StudentTest() { } public StudentTest(String name, int score) { this.name = name; this.score = score; } @Override public String toString() { return "StudentTest{" + "name='" + name + '\'' + ", score=" + score + '}'; } }
输出:
[StudentTest{name='陆小凤', score=98}]
代码3:
import org.junit.Test; import java.util.ArrayList; import java.util.List; /* Collection 无序,不唯一 List:有序,不唯一 ArrayList:数组 LinkedList:链表 * */ public class Demo12 { @Test public void test1(){ List<String> list1 = new ArrayList<>(); list1.add("司马错"); list1.add("司马亮"); list1.add("诸葛亮"); list1.add("诸葛诞"); System.out.println(list1);//[司马错, 司马亮, 诸葛亮, 诸葛诞] list1.add(1,"司马迁"); System.out.println(list1);//[司马错, 司马迁, 司马亮, 诸葛亮, 诸葛诞] List<String> list2 = new ArrayList<>(); list2.add("张翠山"); list2.add("张无忌"); list1.addAll(list2); System.out.println(list1);//[司马错, 司马迁, 司马亮, 诸葛亮, 诸葛诞, 张翠山, 张无忌] list1.addAll(1,list2); System.out.println(list1);//[司马错, 张翠山, 张无忌, 司马迁, 司马亮, 诸葛亮, 诸葛诞, 张翠山, 张无忌] //通过下标获取指定元素 String ele = list1.get(2); System.out.println(ele); //判断是否包含元素 System.out.println(list1.contains("司马亮")); //删除指定下标元素 list1.remove(1); System.out.println(list1); //删除指定元素 list1.remove("司马迁"); System.out.println(list1); //修改指定元素 list1.set(0,"司马错错"); System.out.println(list1);//[司马错错, 张无忌, 司马亮, 诸葛亮, 诸葛诞, 张翠山, 张无忌] System.out.println("list1.isEmpty() = " + list1.isEmpty());//list1.isEmpty() = false System.out.println("list1.size() = " + list1.size());//list1.size() = 7 //list1.clear();清空 System.out.println(list1); //获取一个子集合[]左闭右开 List<String> sublist=list1.subList(0,3); System.out.println("sublist = " + sublist);//sublist = [司马错错, 张无忌, 司马亮] //转换成数组 String[] array = list1.toArray(new String[]{}); for (String s:array){ System.out.println(s); } //获取元素第一次和最后一次出现的下标 System.out.println("list1.indexOf(\"张无忌\") = " + list1.indexOf("张无忌")); System.out.println("list1.lastIndexOf(\"张无忌\") = " + list1.lastIndexOf("张无忌")); //list1.indexOf("张无忌") = 1 //list1.lastIndexOf("张无忌") = 6 } }
代码4
import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class Demo13 { List<String> list1 = new ArrayList<>(); @Before public void testBefore(){ list1.add("李世民"); list1.add("李治"); list1.add("李隆基"); list1.add("李纯"); list1.add("李旦"); } @Test public void test1(){ //普通for循环遍历 for (int i = 0; i <list1.size() ; i++) { String ele = list1.get(i); System.out.println(ele); } System.out.println("-----------------"); //增强for循环 for (String ele:list1){ System.out.println(ele); } System.out.println("-----------------"); //创建iterator对象 Iterator iterator = list1.iterator(); while (iterator.hasNext()){ Object object = iterator.next(); String str = (String)object; System.out.println(str); } System.out.println("-----------------"); //创建listIterator对象,可以hasNext,也可以listIterator.hasPrevious ListIterator<String> listIterator=list1.listIterator(); while (listIterator.hasNext()){ String ele = listIterator.next(); System.out.println(ele); } } }
代码5:
import org.junit.Test; import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Set; /* * */ public class Demo14 { @Test public void test1(){ //多态 Set<String> set1 = new HashSet<>(); set1.add("李克用"); set1.add("李存勖"); set1.add("李丛珂"); set1.add("李嗣源"); set1.add("李丛珂"); System.out.println(set1); //[李存勖, 李克用, 李嗣源, 李丛珂],可以看出不是添加的顺序,且不重复 System.out.println("set1.isEmpty() = " + set1.isEmpty());//set1.isEmpty() = false System.out.println("set1.size() = " + set1.size());//set1.size() = 4 System.out.println("set1.contains(\"李克用\") = " + set1.contains("李克用"));//set1.contains("李克用") = true set1.remove("李丛珂"); System.out.println(set1);//[李存勖, 李克用, 李嗣源] //set1.clear();//清空集合 Set<Integer> set2 = new HashSet<>(); set2.add(10); set2.add(20); Set<Integer> set3 = new HashSet<>(); set3.add(11); set3.add(22); set3.add(33); set2.addAll(set3); System.out.println(set2);//[33, 20, 22, 10, 11] set2.retainAll(set3); System.out.println(set2);//[33, 22, 11] //遍历set,以为无序没有下标,所以只能用增强for或者iterator for(Integer ele:set2){ System.out.println(ele); } //iterator遍历 Iterator<Integer> setIterator=set2.iterator(); while (setIterator.hasNext()){ Integer ele = setIterator.next(); System.out.println(ele); } } @Test public void test2(){ Set<Cat> catSet = new HashSet<>(); catSet.add(new Cat("黑猫",2)); catSet.add(new Cat("白猫",2)); catSet.add(new Cat("黑猫",2)); //因为重写了equals和hashCode方法,所以认为黑猫的对象是重复的 System.out.println("catSet.size() = " + catSet.size());//catSet.size() = 2 } } class Cat{ String name; int age; public Cat() { } public Cat(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Cat{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cat cat = (Cat) o; return age == cat.age && Objects.equals(name, cat.name); } @Override public int hashCode() { return Objects.hash(name, age); } }
代码6:
import org.junit.Test; import javax.xml.crypto.dom.DOMCryptoContext; import java.util.*; /* LinkedHashSet:有序,唯一 LinkedHashSet:添加顺序,元素唯一 TreeSet:自然顺序,元素唯一 * */ public class Demo15 { @Test public void test1(){ LinkedHashSet<String> lhs = new LinkedHashSet<>(); lhs.add("汉武帝"); lhs.add("汉昭帝"); lhs.add("汉宣帝"); lhs.add("汉元帝"); lhs.add("汉昭帝"); System.out.println(lhs);//[汉武帝, 汉昭帝, 汉宣帝, 汉元帝] Set<Integer> set1 = new TreeSet<>(); set1.add(30); set1.add(15); set1.add(10); set1.add(20); set1.add(10); System.out.println(set1);//[10, 20, 30],去重,且按自然排序 Set<String> set2 = new TreeSet<>(); set2.add("a"); set2.add("e"); set2.add("b"); set2.add("z"); System.out.println(set2);//[a, b, e, z] Set<Dog> dogSet = new TreeSet<>(); dogSet.add(new Dog("黑狗",2)); dogSet.add(new Dog("白狗",1)); dogSet.add(new Dog("黄狗",3)); System.out.println(dogSet);//[Dog{name='白狗', age=1}, Dog{name='黑狗', age=2}, Dog{name='黄狗', age=3}] } } class Dog implements Comparable<Dog>{ String name; int age; public Dog() { } public Dog(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Dog o) { return this.age-o.age; } }
代码7:
import org.junit.Test; import java.util.Comparator; import java.util.Objects; import java.util.Set; import java.util.TreeSet; public class Demo16 { @Test public void test1(){ SortPigAge sortPigAge = new SortPigAge(); Set<Pig> pigSet = new TreeSet<>(sortPigAge); pigSet.add(new Pig("天蓬",35,1200)); pigSet.add(new Pig("八戒",30,2000)); pigSet.add(new Pig("钢鬣",32,1500)); pigSet.add(new Pig("元帅",30,1800)); System.out.println(pigSet); //[Pig{name='元帅', age=30, price=1800}, Pig{name='八戒', age=30, price=2000}, Pig{name='钢鬣', age=32, price=1500}, Pig{name='天蓬', age=35, price=1200}]
} } class SortPigAge implements Comparator<Pig>{ @Override public int compare(Pig o1, Pig o2) { if (o1.getAge()==o2.getAge()){ return o1.getPrice()-o2.getPrice(); } return o1.getAge()-o2.getAge(); } } class Pig { String name; int age; int price; public Pig() { } public Pig(String name, int age,int price) { this.name = name; this.age = age; this.price=price; } 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 int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Pig{" + "name='" + name + '\'' + ", age=" + age + ", price=" + price + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pig pig = (Pig) o; return age == pig.age && price == pig.price && Objects.equals(name, pig.name); } @Override public int hashCode() { return Objects.hash(name, age, price); } }
代码8
import com.sun.xml.internal.ws.server.sei.SEIInvokerTube; import org.junit.Test; import java.util.*; /* Map:存储数据,存储键值对,K,V HashMap:1,key无序,唯一, 2,当key重复的时候会替换掉原来的旧值 3,value是可以重复的 LinkedHashMap: TreeMap: * */ public class Demo17 { @Test public void test1(){ Map<Integer,String> map = new HashMap<>(); map.put(1,"王重阳"); map.put(2,"周伯通"); System.out.println(map);//{1=王重阳, 2=周伯通} Map<String,Integer> map2= new HashMap<>(); map2.put("a",100); map2.put("b",90); System.out.println(map2);//{a=100, b=90} } @Test public void test2(){ Map<Integer,String> map = new HashMap<>(); map.put(1,"王重阳"); map.put(2,"王重阳"); map.put(1,"周伯通"); map.put(3,"王重阳"); System.out.println(map);//{1=周伯通, 2=王重阳, 3=王重阳} //判断是否为空,判断大小 System.out.println("map.size() = " + map.size());//map.size() = 3 System.out.println("map.isEmpty() = " + map.isEmpty());//map.isEmpty() = false map.replace(1,"黄药师"); System.out.println(map);//{1=黄药师, 2=王重阳, 3=王重阳} String removename=map.remove(3); System.out.println(removename);//王重阳 System.out.println(map);//{1=黄药师, 2=王重阳} } @Test public void test3(){ Map<String,String> map= new HashMap<>(); map.put("A","王重阳"); map.put("B","黄药师"); map.put("C","欧阳锋"); map.put("D","洪七公"); map.put("E","段智兴"); //遍历获取key,并获取所有value Set<String> set = map.keySet(); for (String s:set){ System.out.println(s); String values=map.get(s); System.out.println(values); } System.out.println("--------------"); //获取所有value Collection<String> allValues=map.values(); Iterator<String> iterator=allValues.iterator(); while (iterator.hasNext()){ String keys=iterator.next(); System.out.println(keys); } System.out.println("--------------"); //判断是否含有key或者value System.out.println("map.containsKey(\"A\") = " + map.containsKey("A"));//map.containsKey("A") = true System.out.println("map.containsValue(\"洪七公\") = " + map.containsValue("洪七公"));//map.containsValue("洪七公") = true System.out.println("--------------"); //map.entrySet()获取键值对,然后遍历 Set<Map.Entry<String, String>> set2 =map.entrySet(); Iterator<Map.Entry<String, String>> iterator1=set2.iterator(); while (iterator1.hasNext()){ Map.Entry<String, String> myenty=iterator1.next(); System.out.println(myenty); System.out.println(myenty.getKey()+"==="+myenty.getValue()); } } }
输出:
A=王重阳 A===王重阳 B=黄药师 B===黄药师 C=欧阳锋 C===欧阳锋 D=洪七公 D===洪七公 E=段智兴 E===段智兴
代码9;
import com.sun.xml.internal.ws.wsdl.parser.MemberSubmissionAddressingWSDLParserExtension; import org.junit.Test; import java.util.*; /* LinkedHashMap:key是有序且是添加顺序,唯一的, */ public class Demo18 { @Test public void test1(){ LinkedHashMap<String,String> linkedHashMap=new LinkedHashMap<>(); linkedHashMap.put("A","王重阳"); linkedHashMap.put("B","黄药师"); linkedHashMap.put("C","欧阳锋"); linkedHashMap.put("C","杨过"); linkedHashMap.put("D","洪七公"); linkedHashMap.put("E","段智兴"); System.out.println(linkedHashMap);//{A=王重阳, B=黄药师, C=杨过, D=洪七公, E=段智兴} System.out.println("----------"); //遍历 Set<Map.Entry<String,String>> myHashSet=linkedHashMap.entrySet(); Iterator<Map.Entry<String,String>> iterator=myHashSet.iterator(); while (iterator.hasNext()){ Map.Entry<String,String> mapEntry=iterator.next(); System.out.println(mapEntry); System.out.println(mapEntry.getKey()+"-----"+mapEntry.getValue()); } System.out.println("----------"); //或者 for (Map.Entry<String,String> ele:myHashSet){ System.out.println(ele); System.out.println(ele.getKey()+"-----"+ele.getValue()); } } }
输出
A=王重阳 A-----王重阳 B=黄药师 B-----黄药师 C=杨过 C-----杨过 D=洪七公 D-----洪七公 E=段智兴 E-----段智兴
Collections工具类
import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; /* *Collections工具类 * * */ public class Demo1 { @Test public void test1(){ List<Integer> list1 = new ArrayList<>(); Collections.addAll(list1,12,3,4,56,43,21,6,74,87,5,62); System.out.println(list1);//[12, 3, 4, 56, 43, 21, 6, 74, 87, 5, 62] //排序 Collections.sort(list1); System.out.println(list1);//[3, 4, 5, 6, 12, 21, 43, 56, 62, 74, 87] //反转,只是反转,不排序 Collections.reverse(list1); System.out.println(list1);//[12, 4, 74, 3, 43, 56, 6, 21, 87, 62, 5] Collections.reverse(list1); //查找 int idx = Collections.binarySearch(list1,56); System.out.println("idx = " + idx);//idx = 7 //打乱顺序 Collections.shuffle(list1); System.out.println(list1);//[12, 4, 74, 3, 43, 56, 6, 21, 87, 62, 5] } @Test public void test2(){ List<String> list1 = new ArrayList<>(); Collections.addAll(list1,"梅超风","陈旋风","陆乘风","小侠龙卷风","陈旋风"); //统计元素出现的次数 int count=Collections.frequency(list1,"陈旋风"); System.out.println(count);//2 List<String> list2 = new ArrayList<>(); Collections.addAll(list2,"丘处机","郝大通","马钰","孙处一","赵志敬"); //集合的复制Collections.copy(目标,源); //要注意目标和源的长度要一致,且会覆盖目标 Collections.copy(list2,list1); System.out.println(list2);//[梅超风, 陈旋风, 陆乘风, 小侠龙卷风, 陈旋风] //元素位置交换 Collections.swap(list1,1,2); System.out.println(list1);//[梅超风, 陆乘风, 陈旋风, 小侠龙卷风, 陈旋风]陈旋风和陆乘风位置交换 //返回一个不能修改的集合 List<String> list3=Collections.unmodifiableList(list1); System.out.println(list3);//[梅超风, 陆乘风, 陈旋风, 小侠龙卷风, 陈旋风] // list3.add("花无缺"); // System.out.println(list3);//java.lang.UnsupportedOperationException报错 } @Test public void test3(){ List<Cat> list1 = new ArrayList<>(); list1.add(new Cat("黑猫",5)); list1.add(new Cat("肥猫",2)); list1.add(new Cat("白猫",1)); list1.add(new Cat("黄猫",3)); System.out.println(list1);//[Cat{name='黑猫', age=5}, Cat{name='肥猫', age=2}, Cat{name='白猫', age=1}, Cat{name='黄猫', age=3}] Collections.sort(list1); System.out.println(list1);//[Cat{name='白猫', age=1}, Cat{name='肥猫', age=2}, Cat{name='黄猫', age=3}, Cat{name='黑猫', age=5}] } } class Cat implements Comparable{ String name; int age; public Cat() { } public Cat(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Cat{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Object o) { Cat cat = (Cat) o; return this.age-cat.age; //如果是倒序比较,也可以如下 //return cat.age-this.age; } }