黑马程序员_集合框架_4

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

JAVA中类是用来封装数据和方法的,而JAVA集合框架就可以理解为用来存储对象的。因为每一个容器对数据的存储方式不同,所以就形成了多种容器。而这些容器有些方法是共有的,然后JAVA工程师在设计的时候,就想到了继承方式,也就形成了JAVA的集合框架。

 

JAVA的集合框架中,ListSet类都是继承于Collection。在Collection中有它们共有的方法。简单的来说就是一些增add方法,删removeretainAllclear方法,判断containisEmptysize、查询 迭代器iterator等方法。下面通过Collection的子类ArrayList来演示这些方法。

import java.util.*;

public class CollectionDemoByArrayList {
public static void main(String[] args) {
Collection<String> col = new ArrayList<String>();
Collection<String> col1 = new ArrayList<String>();
col.add("lailongwei");//add
col1.add("abc1");
col1.add("abc2");
col1.add("abc3");
col.addAll(col1);             //addAll

col.remove("lailongwei");      //remove
col.retainAll(col1);          //移除此 collection 中未包含在指定 collection 中的所有元素。 
col1.clear();                 //清空col1中的元素

System.out.println(col.contains("lailongwei"));            //contains方法
System.out.println(col1.isEmpty());//isEmpty
System.out.println(col.size());               //得到大小

Iterator<String> it = col.iterator();            //使用迭代器
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

迭代器中有hasNest()next()remove()方法。其中remove方法是返回迭代器的Collection中移除的元素。

 

List类的特点是元素内部是有序的,元素是可以重复的。可以重复的原因是该集合体系中有索引。所以凡是有操作索引的方法都是该体系的特有方法。注意索引是从0开始的。特有的方法有:add(int index, E element)get(int index)indexOf(Object o)

lastIndexOf(Object o),listIterator(),set(int index,E element),subList(int fromIndex, int toIndex)。下面使用LinkedList类来演示这些方法

public class ListDemoByLinkedList {

public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("abc1");
list.add("abc2");
list.add("abc3"); 
list.add(2, "abc4");

String string = list.get(2);
int n = list.indexOf("abc3");
int i = list.lastIndexOf("abc4");
list.set(2, "abc5");

ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
String string2 = listIterator.next();
listIterator.add("lailongwei");        //ListIterator特有的方法。可以添加元素
}
LinkedList<String> linkedList = (LinkedList<String>) list.subList(0, 3);
}
}

 

List下有两个常用的子类,一个是ArrayList,一个是LinkedList。他们区别在ArrayList底层的数据结构是数组,所以ArrayList的特点是查询速度快,增删稍慢。而LindedList的特点是增撒快,而查询稍慢。Vector也是List的子类,底层数据结构也是数组。他和ArrayList的区别在雨Vector是同步的,效率低,现在几乎已经被替代了。而LinkedList还有它自身特有的方法。如addFirstaddLast(),removeFirst(),removeLast()。不过这些方法起1.6版本被offerFirst(),offerLast(),peekFirst(),peekLast(),pollFirst()pollLast代替了。List集合判断元素是否相同的依据是元素的equals方法。

 

Set类的特点是元素是无序的(就是存入和取出的顺序不一定一致),元素不可以重复。Set集合的功能和Collection是一致的。Set下有两个常用的子类,一个是HashSet,一个是TreeSet。他们的区别在于,HashSet的底层数据结构是Hash表,而TreeSet的底层数据结构是二叉树。HashSet是通过元素的hashCOde()equals()方法来确定元素的唯一性。如果HashCOde的值一样,才会去判断equals是否相同。下面是HashSet的演示

import java.util.HashSet;

public class HashSetDemo {
public static void main(String[] args) {
HashSet<Student> hashSet = new HashSet<>();
hashSet.add(new Student("abc", 23));
hashSet.add(new Student("abcd", 23));
hashSet.add(new Student("abc", 23));
hashSet.add(new Student("abc", 13));
for (Student student : hashSet) {
System.out.println(student.getName() + "  " +  student.getAge());
}
}
}
class Student{
private String name;
private int age;

public Student(String name, int age) {
this.name = name;
this.age = age;
}

@Override
public int hashCode(){
return name.hashCode() + age * 37;
}

public int getAge() {
return age;
}

public String getName() {
return name;
}

@Override

public boolean equals(Object student){
if (student instanceof Student) {
Student stu = (Student)student;
if (stu.getName().equals(name) && stu.getAge() == age) {
return true;
}
else {
return false;
}
}
else {
return false;
}

}

}

TreeSet是有两种方式来判断唯一性,一种是依靠compareTo。这种方法比较的元素要实现了Comparable接口。是自然排序。另外一种方法是元素不具备比较性,就要在集合初始化的时候把比较器作为参数传递给TreeSet的构造函数。当两种方法都存在是,以比较器的方法为主。下面是演示:

import java.util.Comparator;

import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Person> treeSet = new TreeSet<>();
treeSet.add(new Person("abc", 23));
treeSet.add(new Person("abcd", 23));
treeSet.add(new Person("abc", 23));
treeSet.add(new Person("abc", 13));
for (Person student : treeSet) {
System.out.println(student.getName() + "  " +  student.getAge());
}

TreeSet<Person> treeSet2 = new TreeSet<>(new Comparator<Person>() {

@Override
public int compare(Person o1, Person o2) {
int num = o1.getName().length() - o2.getName().length(); 
if (num == 0) {
return o1.compareTo(o2);
}
return num;
}
});
treeSet2.add(new Person("a", 4));
treeSet2.add(new Person("ab", 1));
treeSet2.add(new Person("abc", 5));
treeSet2.add(new Person("ab", 4));
for (Person student : treeSet) {
System.out.println(student.getName() + "  " +  student.getAge());
}
}
}


class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;

}

@Override

public int compareTo(Person stu) {
int num = name.compareTo(stu.getName());
if (num == 0) {
return age - stu.age;
}
return num;
}
}

Map虽然不是Collection的之类,但是它也是一个集合。Map是个接口。Map的规范形式是Map<K, V>。其中K表示映射类型。V表示映射值类型。Map中常用的子类哟HashMapTreeMapHashMap:底层的数据结构是hash表。可以存入null键和null值,不同步。TreeMap的底层数据结构是二叉树。它们共有的方法有:keySet(),put(K key, V value),entrySet(),get(Object key)等方法。其中keySet()entrySet()方法可以用来遍历Map。下面是一种遍历的演示。

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class MapDemoByTreeMap {
public static void main(String[] args) {
TreeMap<String, Person1> treeMap = new TreeMap<>();
treeMap.put("1", new Person1("a", 45));
treeMap.put("2", new Person1("ab", 45));
treeMap.put("3", new Person1("abc", 45));
treeMap.put("1", new Person1("abcd", 45));
Set<Map.Entry<String, Person1>> entry = treeMap.entrySet();
for (Entry<String, Person1> entry2 : entry) {
System.out.println(entry2.getKey() + " : " + entry2.getValue());

}
Set<String> set = treeMap.keySet();
for (String string : set) {
System.out.println(string + " : " + treeMap.get(string));
}
}
}

class Person1 implements Comparable<Person1>{
private String name;
private int age;
public Person1(String name, int age) {
this.name = name;
this.age = age;
}

public int getAge() {
return age;
}

public String getName() {

return name;

}

@Override

public int compareTo(Person1 stu) {
int num = name.compareTo(stu.getName());
if (num == 0) {
return age - stu.age;
}
return num;
}



@Override
public String toString() {
return name + " " + age; 
}

}


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

详情请查看:http://edu.youkuaiyun.com/heima



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值