黑马程序员 JAVA基础-集合框架(一)

                                  -----------android培训java培训java学习型技术博客、期待与您交流!------------

         在此,分享一下自己学习JAVA的学习心得。有不对的地方请帮忙改正,也希望对想java的同学有帮助!


Java基础

        --集合框架(Collection--List、Set)


集合总结一览:


   Collection:
   |--List:有序,允许有重复值
    ArrayList:数组实现;不保证线程安全,效率高
    Vector:数组实现;线程安全,效率低
  LinkedList:链表实现;不保证线程安全,效率高;
   |--Set:无序,不允许有重复值
   HashSet:哈希表实现;无序
   LinkedHashSet:链表哈希表;有序
   TreeSet:二叉树实现:被排序的


   Map:键值对存储,键不能重复。值无所谓
   |--HashMap:
     |--LinkedHashMap:
   |--TreeMap:
     |--Hashtable:
   
   数据结构:
   数组:查询快,随机获取元素快。添加和删除慢;
   链表:查询慢。添加和删除快
   哈希表:查询块,添加,删除都快,它综合了数组和链表的优点;
   树:具有排序的特性;自然排序和比较器


一、数组的特点:


   1.数组的长度不可变。(局限性)
   2.数组只能存储同类型;
   
   集合类:
   1.集合类本质上就是一个容器,存储对象引用;
   2.对于程序员来说,它似乎可以无限的存储任意数量的对象引用。(与数组的不同,也是我们使用集合的原因,用起来比较方便。)
   3.集合只能存储引用类型的数据。(后边看到能够直接将一个基本数据类型存储到集合中,只是隐式的装箱操作,存储的仍然是引用)
     
   数组和集合的共同点:
   1.都是容器;
   不同点:
   1.数组是定长的。集合的长度可变的。
   2.数组可以存储任何类型的数据;集合只能存储引用类型;


二、Collection接口的常用方法:
   

   1.添加:
   1.boolean add(Object e):确保此 collection 包含指定的元素(可选操作)。如果此 collection 由于调用而发生更改,则返回 true。
   2.boolean addAll(Collection c):将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。如果此 collection 由于调用而发生更改,则返回 true 


   2.删除:
   1.boolean remove(Object o):从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。更确切地讲,如果此 collection 包含一个或多个满足 (o==null ? e==null : o.equals(e)) 的元素 e,则移除这样的元素。如果此调用将移除一个元素,则返回 true 
   2.boolean removeAll(Collection c):移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。如果此 collection 由于调用而发生更改,则返回 true 
   3.void clear():移除此 collection 中的所有元素(可选操作)。


   3.判断:
   1.boolean contains(Object o)如果此 collection 包含指定的元素,则返回 true。当且仅当此 collection 至少包含一个满足 (o==null ? e==null : o.equals(e)) 的元素 e 时,返回 true。 
   2.boolean containsAll(Collection c):如果此 collection 包含指定 collection 中的所有元素,则返回 true。
  3.boolean isEmpty():如果此 collection 不包含元素,则返回 true。


  4.获取:
  1.boolean retainAll(Collection c):两个集合中的交集。移除此 collection 中未包含在指定 collection 中的所有元素。 如果此 collection 由于调用而发生更改,则返回 true 
  2.int size():获取集合的长度:


Collection批量操作的一些方法:


   1、boolean addAll(Collection c):将参数的集合添加到当前的调用集合中。
   2、boolean removeAll(Collection c):移除此 collection 中那些也包含在指定 c 中的所有元素(可选操作)。如果此 collection 由于调用而发生更改,则返回 true 
   3、boolean containsAll(Collection c):如果此 collection 包含指定 collection 中的所有元素,则返回 true。
   4、boolean retainAll(Collection c)两个集合中的交集。移除此 collection 中未包含在指定 collection 中的所有元素。 如果此 collection 由于调用而发生更改,则返回 true。


将Collection中的元素,转换为数组:


   Object[] toArray():


迭代器:

Iterator iterator();

Iterator 对 collection 进行迭代的迭代器。

迭代器的内部实现: 

把取出方式定义在集合的内部,这样取出方式就可以直接访问集合内部的元素。那么取出方式就被定义成了

内部类。而每一个容器的数据结构不同,所以取出的动作细节也不一样。但是都有共性内容判断和取出。那

么可以将共性抽取。

Java练习代码:

public class Demo {
	public static void main(String[] args) {
		Collection list = new ArrayList();
		list.add("章子怡");
		list.add("汪峰");
		list.add("撒贝宁");
		list.add("hello");
		list.add("world");
		list.add("Java");
		
		//使用Iterator遍历
		Iterator it = list.iterator();
		while(it.hasNext()){
			Object obj = it.next();
			System.out.println(obj);
		}}}
    

Collection中的子接口:


list接口:


1、List:元素是有序的,元素可以重复。因为该集合体系有索引。 

2、List接口的特有功能:
      1).添加:
   void add(int index,Object element):在列表的指定位置插入指定元素(可选操作)。将当前处于该位置的元素(如果有的话)和所有后续元素向右移动(在其索引中加 1)。 
      参数:
    index - 要在其中插入指定元素处的索引
      element - 要插入的元素
      2).删除:
      Object remove(int index):移除列表中指定位置的元素(可选操作)。将所有的后续元素向左移动(将其索引减 1)。返回从列表中移除的元素。 
      3).获取:
      Objecdt get(int index):返回列表中指定位置的元素。 
      4).修改:
      Object set(int index,E element):用指定元素替换列表中指定位置的元素(可选操作)。 
      5).List特有的迭代器;
      ListIterator listIterator():获取一个ListIterator迭代器。


    ArrayList接口


1、ArrayList:底层的数据结构使用的是数组结构。特点:查询速度很快。但是增删稍慢。线程不同步。当元素

超过10个,则自动延长,50%延长。

 Java练习代码:

import java.util.ArrayList;

/*
 * 使用ArrayList存储自定义对象
 * 
 */
public class Demo {
	public static void main(String[] args) {
		//1.实例化一个集合
		ArrayList stuList = new ArrayList();
		//2.实例化若干多的Student
		Student stu1 = new Student("张三",22);
		Student stu2 = new Student("李四",23);
		Student stu3 = new Student("王五",24);
		Student stu4 = new Student("王五",24);
		Student stu5 = new Student("王五",24);
		//3.将对象添加到集合
		stuList.add(stu1);
		stuList.add(stu2);
		stuList.add(stu3);
		stuList.add(stu4);
		stuList.add(stu5);
		//4.遍历
		for(int i = 0;i < stuList.size();i++){
			Student stu = (Student)stuList.get(i);
			System.out.println(stu.getName() + "," + stu.getAge());
		}
	}
}

public class Student {
	private String name;
	private int age;
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Student() {
		super();
	}
	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;
	}
}


 LinkedList接口:


1、LinkedList:底层使用的链表数据结构。特点:增删速度很快,查询稍慢。线程不同步。

2、特有功能:
public void addFirst(E e)及addLast(E e)
public E getFirst()及getLast()
public E removeFirst()及public E removeLast()

Java练习代码:

public class Demo {
	public static void main(String[] args) {
		LinkedList list = new LinkedList();
		//addFirst方法具有链表的特性;
		list.addFirst("aaaa");
		list.addFirst("bbbb");
		list.addFirst("cccc");
		//如果使用add方法,将不具有链表的特性了。
		/*list.add("aaa");
		list.add("bbb");
		list.add("ccc");*/
		for(int i = 0;i < list.size();i++){
			System.out.println(list.get(i));
		}
	}
}


Vector:


1、Vector:底层是数组数据结构。线程同步。被ArrayList替代了。因为效率低。当元素超出10个,100%延长。

2、特有方法:
   public void addElement(E obj)
   public E elementAt(int index)

   public Enumeration elements()


Java练习代码:

public class Demo {
	public static void main(String[] args) {
		//1.实例化一个Vector
		Vector list = new Vector();
		//2.添加元素
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		list.addElement("ddd");
		list.addElement("eee");
		//3.遍历
		System.out.println("----使用List的方法遍历-----");
		//使用List的方法
		for(int i = 0;i < list.size();i++){
			System.out.println(list.get(i));
		}
		System.out.println("----使用Vector的方法遍历----");
		//使用Vector的方法
		for(int i = 0;i < list.size() ; i++){
			System.out.println(list.elementAt(i));
		}
	}
}

练习:移除集合中的重复元素:

Java代码:

public class Demo {
	public static void main(String[] args) {
		ArrayList list = new ArrayList();
		
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		list.add("ccc");
		list.add("ddd");
		list.add("bbb");
		list.add("eee");
		list.add("eee");
		list.add("eee");
		
		//取出上面集合中的的重复元素:
		
		//方式一:使用新集合
		/*ArrayList newList = new ArrayList();
		for(int i = 0 ;i < list.size();i++){
			String str = (String)list.get(i);
			if(!newList.contains(str)){
				newList.add(str);
			}
		}
		System.out.println("原集合:" + list);
		System.out.println("新集合:" + newList);*/
		//方式二:使用原数组。类似于选择排序的方式,将每个元素,与后续的其它元素进行比较
		for(int i = 0;i < list.size();i++){
			for(int j = i + 1 ; j < list.size() ; j++){
				if(list.get(i).equals(list.get(j))){
					//如果相同,移除后面的
					list.remove(j);
					j--;
				}
			}
		}
		System.out.println("原集合:" + list);
		
	}
}


   三、Set集合:


         Set(接口):无序(取出的顺序不同于存入的顺序)。

        不允许重复元素,即使是null值,也只能存1个;

怎样保证不重复:
   1.先调用集合中每个对象的hasCode()方法与参数的hasCode()方法的值进行比较,如果相同,继续判断equals()方法;否则,认为不同。
         2.简单说就是:两个对象的hasCode()返回值相同,并且两个对象的equals()方法返回true。认为相同,禁止存储;


Set集合的功能和Collection是一致的。


HashSet类:


         HashSet:底层数据结构是哈希表。是线程不安全的。不同步。
 
  HashSet保证元素唯一,使用元素的hashCode()方法和equals()方法

  1.要保证存储自定义对象的唯一,要重写hashCode()方法和equals()方法;
  2.重写hasCode():通过成员属性换算出新的哈希值:
       1).基本数据类型:直接使用值;
          2).对于引用类型:调用它的hashCode()

Java练习代码:

main方法:

public class Demo {
	public static void main(String[] args) {
		HashSet<Student> set = new HashSet<Student>();
		Student stu1 = new Student("张三",20);
		Student stu2 = new Student("李四",22);
		Student stu3 = new Student("王五",24);
		Student stu4 = new Student("王五",24);
		
		set.add(stu1);
		set.add(stu2);
		set.add(stu3);
	//	set.add(stu3);//添加失败
		set.add(stu4);//添加失败
		
		Iterator<Student> it = set.iterator();
		while(it.hasNext()){
			Student stu = it.next();
			System.out.println(stu.getName() + "--" + stu.getAge());
		}
	}
}
Student类:

public class Student {
	private String name;
	private int age;
	public Student(String name, int age) {
		super();
		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 int hashCode() {
		System.out.println("hashCode()");
		//如果成员属性的值不同,那么就让其返回不同的哈希值
		
		return this.name.hashCode() + age;
	}
	@Override
	public boolean equals(Object obj) {
		System.out.println("equals()");
		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;
	}	
}



LinkdHashSet:


  LinekdHashSet:具有可预知迭代顺序的 Set 接口的哈希表和链接列表实现。
 
  1.由链表保证元素有序;
  2.由哈希表保证元素唯一;
  
   构造函数:
   LinkedHashSet():构造一个带默认初始容量 (16) 和加载因子 (0.75) 的新空链接哈希 set。


Java练习代码:

public class Demo {
	public static void main(String[] args) {
		//1.构造一个LinkedHashSet
		LinkedHashSet<String> set = new LinkedHashSet<String>();
		
		//2.填充内容
		set.add("aaa");
		set.add("bbb");
		set.add("ccc");
		set.add("ddd");
		
		//3.遍历
		Iterator it = set.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
		
	}
}



TreeSet:


  1.使用的是树结构;具有排序功能。(对元素排序,跟之前说的"有序"是不同的,"有序"是指取出时跟存入的顺序相同。)


  2.排序:

    1).自然排序(利用元素本身的排序比较功能):
     A.实现Comparable接口
              B.重写compareTo()方法
    2).比较器(使用了其它的比较器):
     A.自己定义一个类实现Comparator接口
      B.重写compare()方法
      C.实例化TreeSet时,使用构造函数:TreeSet(Comparator com);


        3.线程不安全的,效率高;


Java练习代码:

练习:对学生按年龄排序。

main方法:

public class Demo {
	public static void main(String[] args) {
		//1.先实例化一个TreeSet
		TreeSet<Student> stuSet = new TreeSet<Student>();
		
		//2.实例化一些Student
		Student stu1 = new Student("张三",20);
		Student stu2 = new Student("李四",18);
		Student stu3 = new Student("王五",23);
		
		//3.填充集合
		stuSet.add(stu1);
		stuSet.add(stu2);
		stuSet.add(stu3);
		
		//4.遍历
		Iterator<Student> stuIt = stuSet.iterator();
		while(stuIt.hasNext()){
			Student stu = stuIt.next();
			System.out.println(stu.getName() + "--" + stu.getAge());
		}
	}
}


Student类:

public class Student implements Comparable{
	private String name;
	private int 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;
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public int compareTo(Object o) {
		//根据我们的成员变量来比较
		//按照姓名排序:我们的姓名使用的是String类型,由于String具有比较的方法,我们可以使用String的比较
		Student stu = (Student)o;
		//使用姓名和年龄排序
	//	int num = this.name.compareTo(stu.name);
	//	int num2 = (num == 0 ? this.age - stu.age : num);
		//直接按年龄排序
		int num2 = this.age - stu.age;
		return num2;
	}	
}

































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值