Java基础复习(八)
集合
1.区分数组和集合
-
数组:可以存储不同类型的多个数据,数据类型可以是简单数据类型也可以引用数据类型
缺点:创建的是一个定值,只能存储固定长度的数据,一旦存满了,就不能再继续存储.
-
集合:可以存储不同类型的多个数据,但是只能存储引用数据类型.
- 缺点:只能存储引用数据类型
- 优点:存储空间会随着存储数据的增大而增大,所以可以更加合理的利用内存空间,方法很多,方便我们实现功能.
2.分类
Collection:---接口
* >List---接口
* >>ArrayList--类
* >>Vector ---类
* >>LinkedList--类
>Set---接口
* >>HashSet--类
* >>TreeSet--类
Map:--接口
* >HashMap--类
* >TreeMap--类
*
1.Collection
//Collection中定义是整个集合体系最共性的方法:
Collection collection = new ArrayList<>();
//1.添加:
//boolean add(Object o)
collection.add("java");
collection.add("python");
System.out.println(collection);//重写了toString()
//boolean addAll(Collection<? extends E> c) 一次添加多个元素
Collection collection1 = new ArrayList<>();
collection1.add("BigData");
collection1.add("hadoop");
collection.addAll(collection1);
System.out.println(collection);
//2.删除:
//boolean remove(Object o)
//boolean removeAll(Collection<?> c)
//void clear() clear != null
//collection.remove("java");
//collection.clear();
System.out.println(collection);
//3.判断:
//boolean contains(Object o)
System.out.println(collection.contains("java"));
//boolean containsAll(Collection<?> c) 在判断当前集合是否包含子集合中的元素时,必须包含所有的元素才会返回true
collection.remove("BigData");
System.out.println("haha:"+collection.containsAll(collection1));
//boolean isEmpty() //判断集合是否为空 空 != null
System.out.println(collection.isEmpty());
//boolean equals(Object o)
//4.获取:
//Iterator<E> iterator() //获取集合中的对象
test(collection);
迭代器
原理:开始指针指向第一个位置,使用hasnext方法判断,返回true,再使用next方法获取当前的值,并将指针后移一个位置,依次进行,直到指针指向了集合的末尾,再次调用hasnext方法,返回false,结束遍历.
List和Set
-
List:存储的数据是有序的(元素的存储顺序与添加元素的顺序一致),可以重复的.
public class Demo2 { public static void main(String[] args) { //* List:特有方法,可以操作下标 List list = new ArrayList<>(); //1.增: //void add(int index, E element) //boolean addAll(int index, Collection<? extends E> c) list.add("java"); list.add("html"); list.add(1, "hadoop"); System.out.println(list); //2.删 //E remove(int index) //System.out.println(list.remove(0)); //3.改 //E set(int index, E element) System.out.println(list.set(0, "haha")); //4.查 //ListIterator<E> listIterator() test(list); //返回此列表元素的列表迭代器(按适当顺序)。 //ListIterator<E> listIterator(int index) //List<E> subList(int fromIndex, int toIndex) 左闭右开 List list2 = list.subList(1, 2); System.out.println(list2); //E get(int index) System.out.println(list.get(0)); System.out.println(list); //5.删除全部对象 list.clear(); } //4.查 //ListIterator<E> listIterator() public static void test(List list) { //先获取迭代器对象 ListIterator listIterator = list.listIterator(); //从左到右 while (listIterator.hasNext()) { String object = (String) listIterator.next(); System.out.println("从左到右:"+object); } //从右到左 while (listIterator.hasPrevious()) { String object = (String)listIterator.previous(); System.out.println("从右到左:"+object); } //内部有add,set,remove方法,可以直接对当前位置的元素进行操作 //从左到右 while (listIterator.hasNext()) { String object = (String) listIterator.next(); if (object.equals("haha")) { //在使用迭代器期间,使用list的删除方法直接删除元素,有可能发生错误,所以不要这样做 //list.remove(object); //使用迭代器自带的remove方法 //用迭代器提供的方法,注意:remove,add,set不要同时使用 listIterator.remove(); } System.out.println("从左到右:"+object); } } }
-
Arraylist:底层的数据结构是数组,线程不安全的.特点:查找速度快,添加删除速度慢
-
Vector:底层的数据结构是数组,线程安全的.特点:查找速度快,添加删除速度慢
五种遍历方式
import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; import java.util.function.Consumer; public class VetcorString { public static void main(String[] args) { Vector<String> t=new Vector<String>(); t.add("F"); t.add("o"); t.add("r"); t.add("e"); t.add("v"); t.add("e"); t.add("r"); //第一种 for (String string : t) { System.err.print(string); } //第二种 t.forEach(new Consumer<String>() { @Override public void accept(String t) { // TODO Auto-generated method stub System.out.print(t); } }); //第三种 for (int i = 0; i < t.size(); i++) { System.out.print(t.get(i)); } //第四种 Iterator<String> it = t.iterator(); while (it.hasNext()) { String string = (String) it.next(); System.err.print(string); } //第五种 Enumeration<String> enume = t.elements(); while(enume.hasMoreElements()){ System.out.print(enume.nextElement().toString()); } } }
-
LinkedList:底层是链表,线程不安全的.特点:查找速度慢,添加删除速度快.
public class Demo4 { public static void main(String[] args) { // LindedList // 特有的方法: LinkedList linkedList = new LinkedList<>(); // addFirst()//始终在首位添加 // addLast()//始终在末尾添加 linkedList.addFirst("java"); linkedList.addLast("html"); linkedList.add("hadoop"); linkedList.add(1, "spark"); linkedList.addFirst("BigData"); System.out.println(linkedList); // getFirst()//获取的对象不存在会发生异常 // getLast() linkedList.clear(); //String value = (String)linkedList.getFirst();//NoSuchElementException 没有这个元素异常 //System.out.println(value); // removeFirst()//删除的对象不存在会发生异常 // removeLast() // 从jdk1.6开始出现以下方法 // offerFirst() // offerLast() // peekFirst()//获取的对象不存在会返回null // peekLast() System.out.println(linkedList.peekFirst()); // pollFirst()//删除的对象不存在会返回null // pollLast() } }
使用list存自定义的类对象并去重
package Collection; import java.util.ArrayList; import java.util.ListIterator; class Person{ String name; int age; public Person(){} public Person(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; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } //重写equals函数,自己制定比较规则:根据年龄和姓名比较 @Override public boolean equals(Object obj) { if(!(obj instanceof Person)) { throw new ClassCastException("当前的对象不是Person类型的"); } Person person = (Person)obj; return this.name.equals(person.name) && this.age==person.age; } } public class demo4 { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add(new Person("bingbing",18)); list.add(new Person("chenchen",98)); list.add(new Person("hanghang",108)); list.add(new Person("zhangsan",28)); list.add(new Person("bingbing",18)); System.out.println(list); ArrayList list1 = new ArrayList(); ListIterator listIterator = list.listIterator(); while (listIterator.hasNext()) { Person object = (Person) listIterator.next(); if(!list1.contains(object)) { list1.add(object); } } System.out.println("去重后的结果:"+list1); } }
-
-
Set,存储的数据是无序的,不可以重复
-
HashSet:底层是哈希表,线程不安全的
-
TreeSet:底层是二叉树,线程不安全的
-
HashSet:
-
原理:是通过调用元素的hashCode和equals方法实现去重,首先调hashCode方法,拿到当前对象的哈希码值,去让两个对象的哈希码值进行比较,如果不同,直接认为是两个对象,不再去调equals,如果相同,再继续调用equals方法,返回true认为是一个对象,返回false认为是两个对象
-
//* 实例:使用HashSet实现Person对象的存储 // * 比较规则自己指定:按照年龄和姓名比,相同认为是一个人 //* 分析:要重写hashCode和equals方法 public class Demo7 { public static void main(String[] args) { Set set = new HashSet<>(); //说明Set本身的add方法内部实现的去重功能,默认调用的是元素的hashCode和equals方法 //String类已经默认重写了hashCode和equals方法 set.add("java"); set.add("hadoop"); set.add("spark"); set.add("HDFS"); set.add("HDFS"); set.add("Mapreduce"); System.out.println("result1:"+set); Set set1 = new HashSet<>(); set1.add(new Person1("bingbing",18)); set1.add(new Person1("zhangsan",28)); set1.add(new Person1("chenchen",98)); set1.add(new Person1("bingbing",18)); System.out.println(set1); } } class Person1{ String name; int age; public Person1() { super(); // TODO Auto-generated constructor stub } public Person1(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person1 [name=" + name + ", age=" + age + "]"; } //重写hashCode方法 @Override public int hashCode() { return name.hashCode()+age*1000; } //重写equals方法 @Override public boolean equals(Object obj) { //自己制定比较规则:根据年龄和姓名比较 //容错处理 if (!(obj instanceof Person1)) { throw new ClassCastException("当前的对象不是Person1类型的"); } //向下转型 Person1 person = (Person1)obj; return this.name.equals(person.name) && this.age==person.age; } }
-
TreeSet
-
可以实现排序和去重。(自然排序和人工排序)
-
人工排序的优先级高于默认排序
第一种(实现Comparable接口重写compareTo方法,自然排序)
-
/*第一种(实现Comparable接口的compareTo方法) 实例:在TreeSet中存入Person1类的对象 *并按照年龄和姓名实现排序,去重 *分析:需要实现Comparable接口的compareTo方法 * */ public class Demo8 { public static void main(String[] args) { Set set = new TreeSet<>(); /* * TreeSet的add方法实现的排序,去重.通过调用元素的compareTo方法 * String类已经实现了Comparable接口 */ set.add("java"); set.add("hadoop"); set.add("spark"); set.add("HDFS"); set.add("HDFS"); set.add("Mapreduce"); System.out.println("result1:"+set); //没有实现Compareble接口的对象不能当做TreeSet的元素,否则报异常ClassCastException Set set1 = new TreeSet<>(); set1.add(new Person2("bingbing",18)); set1.add(new Person2("zhangsan",28)); set1.add(new Person2("chenchen",98)); set1.add(new Person2("bingbing",18)); System.out.println(set1); } } class Person2 implements Comparable{ String name; int age; public Person2() { super(); // TODO Auto-generated constructor stub } public Person2(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person2 [name=" + name + ", age=" + age + "]"; } @Override public int compareTo(Object o) { //根据自己制定的规则比较 //根据年龄和姓名比较 //容错处理 if (!(o instanceof Person2)) { throw new ClassCastException("类型转换错误"); } //向下转型 Person2 person2 = (Person2)o; //先比姓名 int num = this.name.compareTo(person2.name); //再按照年龄比 return num==0?this.age-person2.age:num; } }
使用实现了Comparator接口的compare()方法的比较器对象进行比较(人工排序)
/* 将人存入TreeSet,通过Comparator实现Person2的排序和比较 *规则:只要姓名和年龄相同认为是一个人 */ package Collection; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class demo7 { public static void main(String[] args) { Set set = new TreeSet<String>(); set.add("java"); set.add("hadoop"); set.add("spark"); set.add("HDFS"); set.add("HDFS"); set.add("Mapreduce"); System.out.println(set); TreeSet treeSet = new TreeSet(); treeSet.add(new Person2("bingbing",18)); treeSet.add(new Person2("zhangsan",28)); treeSet.add(new Person2("chenchen",98)); treeSet.add(new Person2("bingbing",18)); System.out.println(treeSet); } } class Person3 implements Comparator{ String name; int age; public Person3() { super(); // TODO Auto-generated constructor stub } public Person3(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person2 [name=" + name + ", age=" + age + "]"; } @Override public int compare(Object o1, Object o2) { if(!(o1 instanceof Person3)) { throw new ClassCastException("error"); } if(!(o2 instanceof Person3)) { throw new ClassCastException("error"); } Person3 person1 = (Person3) o1; Person3 person2 = (Person3) o2; int num = person1.name.compareTo(person2.name); return num==0?person1.age-person2.age:num; } }
-
-