【JavaSE笔记】集合(一)_Collection

来源:互联网 发布:泰安中商网络 编辑:程序博客网 时间:2024/05/21 10:42

1. 对象数组

a. 数组既可以存储基本数据类型,也可以存储引用类型。它存储引用类型的时候的数组就叫对象数组
b. 现阶段学习的容器有哪些?
i. 数组:里面的长度是固定的
ii. 字符缓冲区:始终返回的是一个字符串

2. 集合(Collection)

a. 集合由来:

Java -- 面向对象 -- 操作很多对象 -- 存储 -- 容器(数和StringBuffer) -- 数组,而数组的长度固定,所以不适合做变化的需求,Java就提供了集合供我们使用。

b. 集合和数组的区别

i. 长度区别:

1) 数组固定
2) 集合可变

ii. 内容区别:

1) 数组可以是基本类型,也可以是引用类型
2) 集合只能是引用类型

iii. 元素内容

1) 数组只能存储同一种类型
2) 集合可以存储不同类型(一般都存储同一种类型)

c. 集合框架体系图

由于需求不同,Java就提供了不同的集合类。这多个集合类的数据结构不同,但是它们都是要提供存储和遍历功能的。
Collection
|--List
|--ArrayList
|--Vector
|--LinkedList
|--Set
|--HashSet
|--TreeSet

d. Collection的功能

i. 添加功能:

boolean add(Object obj)   添加一个元素
boolean addAll(Collection c)   添加一个集合中的元素

ii. 删除功能:

boolean remove(Object o)   删除指定的元素
boolean removeAll(Collection c)   删除一个集合中的元素
void clear()   删除一个集合中的所有元素

iii. 判断功能:

boolean contains(Object o)   判断该集合中是否包含指定的元素
boolean containsAll(Collection c)   判断是否包含一个集合中的元素
boolean isEmpty()   判断集合是否为空

iv. 获取功能:

Iterator iterator()  表示对集合中的元素进行迭代(遍历)

v. 长度功能:

int size()   返回此 collection 中的元素数。

vi. 交集功能:

boolean retainAll(Collection c)  仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。

vii. 集合转换成数组:

Object[ ] toArray() 

public class Collection类的添加功能 {public static void main(String[] args) {//创建两个集合对象Collection c1 = new ArrayList();c1.add("yang1");c1.add("yang2");c1.add("yang3");Collection c2 = new ArrayList();c2.add("yang2");c2.add("yang3");c2.add("yang4");Collection c3 = new ArrayList();c3.addAll(c2);System.out.println(c1);//[yang1, yang2, yang3]System.out.println(c2);//[yang2, yang3, yang4]System.out.println(c3);//[yang2, yang3, yang4]}}


public class Collection类的判断功能 {public static void main(String[] args) {//创建两个集合对象Collection c1 = new ArrayList();c1.add("yang1");c1.add("yang2");c1.add("yang3");Collection c2 = new ArrayList();c2.add("yang2");c2.add("yang3");c2.add("yang4");Collection c3 = new ArrayList();c3.add("yang2");c3.add("yang3");c3.add("yang4");//boolean contains(Object o)   如果此 collection 包含指定的元素,则返回 true。System.out.println(c1.contains("yang3"));//trueSystem.out.println("————————");//boolean containsAll(Collection c)   如果此 collection 包含指定 collection 中的所有元素,则返回 true。System.out.println(c1.contains(c2));//falseSystem.out.println("————————");//boolean equals(Object o)  比较此 collection 与指定对象是否相等。System.out.println(c2.equals(c3));//trueSystem.out.println("————————");//boolean isEmpty()  如果此 collection 不包含元素,则返回 true。System.out.println(c1.isEmpty());//false}}

public class Collection类的删除功能 {public static void main(String[] args) {Collection c1 = new ArrayList();c1.add("yang1");c1.add("yang2");c1.add("yang3");System.out.println("c:"+c1);//c:[yang1, yang2, yang3]c1.remove("yang2");System.out.println(c1);//[yang1, yang3]c1.removeAll(c1);System.out.println(c1);//[]//c1.clear();//System.out.println(c1);}}

e. Collection集合的遍历

i. 把集合转成数组

ii. 迭代器(集合专用)


import java.util.ArrayList;import java.util.Collection;public class 遍历_数组的方式 {public static void main(String[] args) {//创建集合对象Collection c = new ArrayList();//创建学生对象 添加至集合中c.add(new Student("Tom",20));c.add(new Student("Jack",21));c.add(new Student("Lin",23));c.add(new Student("Bush",24));//将集合转换成数组:Object[] o = c.toArray();for (int i = 0; i <o.length ; i++) {Student s = (Student) o[i];System.out.println(s.getName()+"---"+s.getAge());}}}//out:Tom---20//Jack---21//Lin---23//Bush---24

import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class 遍历_迭代器 {public static void main(String[] args) {//创建集合对象Collection c = new ArrayList();//创建学生对象 添加至集合中c.add(new Student("Tom",20));c.add(new Student("Jack",21));c.add(new Student("Lin",23));c.add(new Student("Bush",24));Iterator t = c.iterator();while(t.hasNext()){Student s = (Student) t.next();System.out.println(s.getName()+"---"+s.getName());}}}//out://Tom---Tom//Jack---Jack//Lin---Lin//Bush---Bush


f. 迭代器

i. 迭代器是集合获取元素的方式。
ii. 迭代器是依赖集合而存在的。

iii. 迭代器的原理和源码码:

interface Iterator{boolean hasNext() ;Object next();}public interface Iterable {Iterator iterator();}public interface Collection extends Iterable{public Iterator iterator() {        return new Itr(); //Itr:类    }        //具体的类:内部类的另一种形式    private class Itr implements Iterator { //Itr是Iterator接口的子实现类          public boolean hasNext() {//重写了hasNext()       return cursor != size;      }          public Object next() {          }    }}collection c = new ArrayList();c.add("hello");c.add("world");c.add("java");Iterator it = c.iterator();//Iterator it = new Itr() ;//接口多态(开发中经常用)while(it.hasNext){String s = (String)it.next();System.out.println(s);}

3. List

a. List集合是Collection集合的子接口,接口与接口的关系是继承关系!

特点:List集合是一个有序(元素存储和取出是一致的!)的集合,是可以有重复的元素

b. List的特有功能:

i. 添加功能:

void add(int index,Object element)   在指定位置添加指定的元素

ii. 删除功能:

Object remove(int index)   删除指定位置的元素,返回的就是删除的元素

iii. 获取功能:

Object get(int index)   获取指定位置的元素

iv. 修改功能:

Object set(int index,object element)   将指定位置的元素用element该元素替代,返回的是需要被替代的元素

v. 迭代器功能:

ListIterator listIterator()   ListIterator继承自 Collection中的Iterator接口


import java.util.ArrayList;import java.util.List;public class List类的常用方法 {public static void main(String[] args) {//创建List集合对象  ;List l = new ArrayList<>();//添加元素;l.add("I");l.add("want");l.add("something");l.add("just");l.add("like");l.add("this");System.out.println("List:"+l);//List:[I, want, something, just, like, this]//void add(int index,Object element)    在指定位置添加指定的元素//在该索引对应的元素的位置前面添加一个新的元素l.add(0, "NEW");//l.add(12,"NEW");//IndexOutOfBoundsException:角标越界System.out.println("List"+l);//List[NEW, I, want, something, just, like, this]System.out.println("——————————————————————————");//Object remove(int index)    删除指定位置的元素System.out.println(l.remove(5));//likeSystem.out.println("List:"+l);//List:[NEW, I, want, something, just, this]System.out.println("——————————————————————————");//Object get(int index)    获取指定位置的元素System.out.println(l.get(5));//thisSystem.out.println("——————————————————————————");//Object set(int index,object element):将指定位置的元素用element该元素替代,返回的是需要被替代的元素System.out.println(l.set(2,"TiHuan"));//wantSystem.out.println("List:"+l);//List:[NEW, I, TiHuan, something, just, this]}}

c. List集合遍历方式:

i. 由size()和get()结合。
ii. Iterate iterate();

iii. ListIterate listiterate();

import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class List遍历 {public static void main(String[] args) {//创建集合对象List list = new ArrayList();//创建并添加元素list.add("hello");list.add("world");list.add("java");//遍历集合Iterator it = list.iterator();while(it.hasNext()) {String s =(String) it.next();System.out.println(s);}System.out.println("----------");//for(size()/get()方法)for(int x=0; x<list.size(); x++) {String s =(String) list.get(x);System.out.println(s);}}}/*out:helloworldjava----------helloworldjava*/


d. List集合专有迭代遍历方式

ListIterator listIterator() ;
i. ListIterator接口(extends Iterator)的方法:
1) boolean hasNext()   表示正向遍历:是否有下一个可以迭代的元素
2) Object next()  获取下一个元素
3) boolean hasPrevious()  表示逆向遍历:是否有上一个可以迭代的元素
4) Object previous()  返回列表中的前一个元素
ii. 可以逆向遍历,但是要先正向遍历,所以无意义,基本不使用。

e. 并发修改异常(java.util.ConcurrentModificationException

i. 产生并发修改异常的原因:

当我们给集合中添加了新的字符串,迭代器不知道集合中是否添加了一个新的元素,所以产生这个异常!

ii. 两种解决方式:

1) 使用迭代器遍历,迭代器添加,Iterator接口没有添加功能,所有使用列表迭代器:ListIterator

2) 使用集合遍历,使用集合添加

import java.util.ArrayList;import java.util.List;import java.util.ListIterator;public class 并发修改异常 {public static void main(String[] args) {//创建集合对象List a = new ArrayList();//添加字符串a.add("I");a.add("Want");a.add("Something");a.add("Just");a.add("Like");a.add("This");/*//遍历集合的元素,使用迭代器遍历Iterator i = a.iterator();while(i.hasNext()){String s = (String) i.next();//判断if(s.equals("Just")){a.add("YF");}}System.out.println(a);*///java.util.ConcurrentModificationException 并发修改异常//两种解决方式://1.使用迭代器遍历,迭代器添加,Iterator接口没有添加功能,所有使用列表迭代器:ListIteratorListIterator i = a.listIterator();while(i.hasNext()){String s = (String) i.next();if(s.equals("Just")){i.add("YF");}}System.out.println(a);//[I, Want, Something, Just, YF, Like, This]//2.使用集合遍历,使用集合添加for(int x =0 ;x<a.size();x++){String s = (String) a.get(x);//判断有world,采用集合添加,在末尾添加if(s.equals("Want")){a.add("Fan");}}System.out.println(a);//[I, Want, Something, Just, YF, Like, This, Fan]}}


f. 常见数据结构

i. 栈:先进后出
ii. 队列:先进先出
iii. 数组:查询快,增删慢
iv. 链表:查询慢,增删快

g. List的子类特点(面试题)

i. ArrayList
底层数据结构是数组,查询快,增删慢,线程不安全,不同步,效率高
ii. Vector
底层数据结构是数组,查询快,增删慢,线程安全,同步,效率低
iii. LinkedList
底层数据结构数链表,查询慢,增删快,线程不安全,不同步,效率高
应用场景:ArrayList:开发中用的非常多!
如果给一个需求,不知道使用谁的时候,都使用ArrayList

h. List集合的练习:


4. ArrayList

a. 底层数据结构是数组,查询快,增删慢,线程不安全(多线程中讲),效率高
b. List集合的子类遍历集合中的元素可以使用的任何迭代遍历方式:普通for循环、itreator()

c. ArrayList相关案例:需求:ArrayList去除集合中字符串的重复值(字符串的内容相同)

import java.util.ArrayList;import java.util.Iterator;public class 练习1 {public static void main(String[] args) {ArrayList a = new ArrayList();a.add("I");a.add("Want");a.add("Something");a.add("Just");a.add("Just");a.add("Like");a.add("Want");a.add("Just");a.add("This");System.out.println(a);for (int i = 0; i < a.size()-1; i++) {for(int j =i+1;j<a.size();j++){if(a.get(i).equals(a.get(j))){a.remove(j);j--;}}}System.out.println(a);System.out.println("——————————");//迭代器方式Iterator t = a.iterator();while(t.hasNext()){String s = (String) t.next();System.out.println(s);}}}/*out:[I, Want, Something, Just, Just, Like, Want, Just, This][I, Want, Something, Just, Like, This]——————————IWantSomethingJustLikeThis*/

import java.util.ArrayList;import java.util.Iterator;//需求:ArrayList去除集合对象的重复的成员信息(成员变量的值是一样)//现在集合存储的是引用类型的对象,而一个类的对象,有一个equals()方法,如果不重写,默认用Object中的equals()//默认比较的是地址值;在Student类中重写equals方法,比较是内容是否相同class Student{private String name;private int age;public Student() {super();}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;}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + "]";}//重写equals方法 比较的是内容@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}public class 练习2 {public static void main(String[] args) {//创建ArrayList集合对象ArrayList a = new ArrayList();//创建5个学生对象  添加至集合a.add(new Student("Tom",21));a.add(new Student("Peter",23));a.add(new Student("Ber",21));a.add(new Student("Peter",23));a.add(new Student("Tom",21));a.add(new Student("Peter",23));//创建新集合ArrayList aa = new ArrayList();//遍历旧集合Iterator t = a.iterator();while(t.hasNext()){Student s = (Student) t.next();if(!aa.contains(s)){aa.add(s);}}//遍历新集合Iterator tt = aa.iterator();while(tt.hasNext()){Student s = (Student) tt.next();System.out.println(s.getName()+"---"+s.getAge());}}}


5. Vecotr

a. 底层数据结构是数组,查询快,增删慢,线程安全,同步,效率低
b. 特有功能:
i.  public void addElement(Object obj)   给Vector集合中添加元素
ii. public Object elementAt(int index)类似get(int index):获取指定索引处的元素
iii.public Enumeration elements()       类似Iterator iterator()获取迭代器对象
iv.boolean hasMoreElements()          类似hasNext():判断是否有下一个可以迭代的元素
v. Object nextElement()                      类似next()
import java.util.Vector;import java.util.Enumeration;public class VectorDemo {public static void main(String[] args) {//创建Vector集合对象Vector v = new Vector();//添加元素v.addElement("I");v.addElement("Want");v.addElement("Something");v.addElement("Just");v.addElement("Like");v.addElement("This");//遍历Vector集合:普通的for循环for(int i =0 ;i<v.size();i++){//public Object elementAt(int index)String s = (String) v.elementAt(i);System.out.println(s);}System.out.println("————————————————");//获取迭代器对象:Enumeration en = v.elements();while(en.hasMoreElements()){String s = (String) en.nextElement();System.out.println(s);}}}/*out:IWantSomethingJustLikeThis————————————————IWantSomethingJustLikeThis*/



6. LinkedList

a. 底层数据结构是链表,查询慢,增删快,线程不安全,效率高!
b. 特有功能
i. 添加相关的方法:
public void addFirst(Object e)
public void addLast(Object e)
ii. 获取相关的方法:
public Object getFirst()  返回此列表的第一个元素
public Object getLast()  返回此列表的最后一个元素
iii. 删除相关的方法:
public Object removeFirst() 删除此列表的第一个元素
public Object removeLast() 删除此列表的最后一个元素
import java.util.LinkedList;public class LinkedListDemo  {public static void main(String[] args) {//创建LinkedList集合对象LinkedList link = new LinkedList() ;//给集合中添加元素link.add("hello");link.add("world");link.add("java");System.out.println("link:"+link);//添加相关的方法:link.addFirst("Yang");link.addLast("Fan");System.out.println(link);System.out.println("————————————————————————");//获取相关的方法:System.out.println("getFirst:"+link.getFirst());System.out.println("getLast:"+link.getLast());System.out.println("————————————————————————");//删除相关的方法:System.out.println("removeFirst:"+link.removeFirst());System.out.println("removeLast:"+link.removeLast());System.out.println("link:"+link);}}
/*out:
link:[hello, world, java][Yang, hello, world, java, Fan]————————————————————————getFirst:YanggetLast:Fan————————————————————————removeFirst:YangremoveLast:Fanlink:[hello, world, java]*/


 
原创粉丝点击