Getting Started with Java Tutorial twelve (collections and generics)

The length of the Java array is immutable. However, in many cases, practical applications, can not determine the amount of data. These data are not suitable for use an array to save, this time you need to use the collection.

Java collection is like a container for objects stored Java classes. Some things inside containers stored inside the container is not operational, like the bottle in the water, in addition to its load and poured out, you can not perform other operations, but it is easy to load and poured out; and some things inside containers stored inside the container can be operated, for example, put the clothes closet, not only the clothes stored in the closet, you can also put the clothes in an orderly manner, in order to quickly find when in use, but It is not easy to remove. Java collection features more than analogy of these containers, some of which are easy to put in and taken out, some are easy to find. In the collection are often used to make generic collection more secure.

set

Collections are located java.util package, which provides a unified architecture and operation of a set of objects represented, comprising a collection of a large number of interfaces, as well as their operation and implementation class of algorithms for these interfaces. Is a set of an object, but it represents a group of objects, Java set value actually stored is a reference to the object, the value of the basic data types can not be stored.

Collection interfaces

Library is a collection of a set frame, comprising a set of interface. Interface is a set of abstract data types, providing the content indicated by the set may be a separate operation.
Collection Interface: The interface is the most basic set of interfaces, a Collection represents an element.
List Interface: The interface implements the Collection interface. List is an ordered set, allowing the same elements. List can be accurately controlled using each element is inserted, the user can use index (List elements in position, similar to the array index) to access elements in List, like arrays.
Set Interface: The interface also implements the Collection interface. It can not contain duplicate elements, SortedSet Set is the set in ascending order.
Map Interface: contains key-value pairs, Map can not contain duplicate keys. Map is a collection SortedMap ascending order.

Interface implementation class

The Java platform provides a number of data collection interface implementation class. Set achieved, for example have a common interface and HashSet TreeSet, which can accommodate all types of objects, but can not guarantee the sequence order permanent change

List interface to achieve common class of ArrayList and LinkedList, they can also accommodate all types of objects include null, and the storage location elements are guaranteed.

Map implementation class mapping a HashMap, can be realized a key value mapped to.
HashSet: In order to optimize query speed and design Set. It is based, HashSet HashMap implemented using the underlying HashMap to hold all the elements, is relatively simple.
TreeSet: This class not only to achieve Set interface, but also realized java.util.SortedSet interfaces, the implementation class is an ordered Set, so you can extract an ordered sequence from a Set inside.
ArrayList: List with a array to achieve, can be fast random access, high efficiency and achieve an array of variable size.
LinkedList: optimized access order, but the random access speed is relatively slow. In addition, it also addFirst (), addLast (), getFirst (), getLast (), removeFirst () and removeLast () method and the like, which can as a stack (Stack), or a queue (Queue) to use.

Collection Interface

Collection interface is the parent interface Interface List and Set interfaces, it is not normally used directly. Collection interface defines the general method may be implemented on a set of basic operations by these methods. Because the interface List and Set interfaces inherited from the Collection interface, so you can also call these methods

boolean add(E e)    向集合中添加一个元素,E 是元素的数据类型
boolean addAll(Collection c)    向集合中添加集合 c 中的所有元素
void clear()    删除集合中的所有元素
boolean contains(Object o)  判断集合中是否存在指定元素
boolean containsAll(Collection c)   判断集合中是否包含集合 c 中的所有元素
boolean isEmpty()   判断集合是否为空
Iterator<E>iterator()   返回一个 Iterator 对象,用于遍历集合中的元素
boolean remove(Object o)    从集合中删除一个指定元素
boolean removeAll(Collection c) 从集合中删除所有在集合 c 中出现的元素
boolean retainAll(Collection c) 仅仅保留集合中所有在集合 c 中出现的元素
int size()  返回集合中元素的个数
Object[] toArray()  返回包含此集合中所有元素的数组
public static void main(Strmg[] args)
{
    ArrayList list1=new ArrayList();    //创建集合 iist1
    ArrayList list2=new ArrayList();    //创建集合 Iist2
    list1.add("one");    //向 list1 添加一个元素
    list1.add("two");    //向 list1 添加一个元素
    list2.addAll(list1);    //将 list1 的所有元素添加到 list2
    list2.remove(0);   //删除第一个元素 
}

List collection

List interface Collection interface, it has two main implementation class: ArrayList and LinkedList class category. Allow duplicates within the List collection. Set is the set of different elements in the set are ordered List, the List elements can be retrieved based on the index set position, a first index element added to the List set to 0, the second 1 ,So on and so forth

ArrayList class

ArrayList class provides a fast index-based access method members, the members of the tail of adding and deleting support is good. Use ArrayList collection was created to allow for the collection of elements fast random access

ArrayList():构造一个初始容量为 10 的空列表。
ArrayList(Collection<?extends E>c):构造一个包含指定 Collection 的元素的列表,这些元素是按照该 Collection 的迭代器返回它们的顺序排列的。

ArrayList class contains all the methods other than the Collection interface, further comprising an interface List

E get(int index)    获取此集合中指定索引位置的元素,E 为集合中元素的数据类型
int index(Object o) 返回此集合中第一次出现指定元素的索引,如果此集合不包含该元
素,则返回 -1
int lastIndexOf(Obj ect o)  返回此集合中最后一次出现指定元素的索引,如果此集合不包含该
元素,则返回 -1
E set(int index, E element) 将此集合中指定索引位置的元素修改为 element 参数指定的对象。
此方法返回此集合中指定索引位置的原元素
List<E> subList(int fromlndex, int tolndex)返回一个新的集合,新集合中包含 fromlndex 和 tolndex 索引之间的所有元素。包含 fromlndex 处的元素,不包含 tolndex 索引处的元素
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");

list.get(0);//得到1

List sublist=new ArrayList();
sublist=list.subList(0,2); //subList 为1,2

LinkList class

LinkedList class objects stored linked list structure, the advantage of this structure is easy to insert or delete elements to the collection. Frequently insert and delete elements, the effect of using high LinkedList ArrayList class analogy to the collection
LinkedList classes and interfaces in addition contains a Connection Interface List

void addFirst(E e)  将指定元素添加到此集合的开头
void addLast(E e)   将指定元素添加到此集合的末尾
E getFirst()    返回此集合的第一个元素
E getLast() 返回此集合的最后一个元素
E removeFirst() 删除此集合中的第一个元素
E removeLast()  删除此集合中的最后一个元素
LinkedList<String> products=new LinkedList<String>();    //创建集合对象
String product1=new String("product1");
String product2=new String("product2");

products.getFirst();//得到product1

Set collection

Set collection also implements the Collection interface, which has two main implementation class: HashSet and TreeSet class category. Set collection objects are not sorted in a particular manner, simply the objects to the collection, the collection can not contain duplicate objects, and at most only contains a null element

HashSet

HashSet class in accordance with a hashing algorithm to store the elements in a collection, using a hashing algorithm can improve storage speed collection of elements when adding an element to the collection of Set, HashSet will call the element hashCode () method to get their ha Greek symbol, and then calculates the position of the storage element in the set according to this hash code,

HashSet():构造一个新的空的 Set 集合。
HashSet(Collection<? extends E>c):构造一个包含指定 Collection 集合元素的新 Set 集合。其中,“< >”中的 extends 表示 HashSet 的父类,即指明该 Set 集合中存放的集合元素类型。c 表示其中的元素将被存放在此 Set 集合中。

HashSet hs=new HashSet();                     //调用无参的构造函数创建HashSet对象
HashSet<String> hss=new HashSet<String>();    //创建泛型的 HashSet 集合对象
String name=new String("HelloWorld");
String name1=new String("HelloWorld1");
hss(name); 
hss(name1); 

If you add two identical elements to Set the collection, after addition of the added elements will cover the front, i.e., the same elements will not be set in the Set

TreeSet

TreeSet class implements the Set interface and SortedSet interface. SortedSet interface is a sub-interface Set interface can be achieved in ascending order the collection. TreeSet class object can only achieve a sort Comparable interface, because there is a Comparable interface compareTo (Object o) a method for comparing two objects

包装类(BigDecimal、Biglnteger、 Byte、Double、
Float、Integer、Long 及 Short) 按数字大小比较
Character   按字符的 Unicode 值的数字大小比较
String  按字符串中字符的 Unicode 值的数字大小比较

TreeSet class implements all methods except Collection interface, there are the following methods

E first()   返回此集合中的第一个元素。其中,E 表示集合中元素的数据 类型
E last()    返回此集合中的最后一个元素
E poolFirst()   获取并移除此集合中的第一个元素
E poolLast()    获取并移除此集合中的最后一个元素
SortedSet<E> subSet(E fromElement,E toElement)  返回一个新的集合,新集合包含原集合中 fromElement 对象与 toElement
对象之间的所有对象。包含 fromElemen t对象,不包含 toElement 对象
SortedSet<E> headSet<E toElement〉   返回一个新的集合,新集合包含原集合中 toElement 对象之前的所有对象。
不包含 toElement 对象
SortedSet<E> tailSet(E fromElement) 返回一个新的集合,新集合包含原集合中 fromElement 对象之后的所有对
象。包含 fromElement 对象
TreeSet<Double> treeSet=new TreeSet<Double>(); 
treeSet.add(0.02);
treeSet.add(0.01);
treeSet.add(0.03);
for(int i=0;i<treeSet.toArray().length;i++)
{
     System.out.print(treeSet.toArray.toArray()[i]); //依次输出 0.01,0.02,0.03
}
SortedSet<Double> headTreeSet =scores.headSet(0.02); //headTreeSet内只有0.01

You can only add objects of the same type of data collection to TreeSet when the natural order, otherwise it will throw ClassCastException.

Map collection

Map is a key - value pair (key-value) set, Map set each element contains a key object and a target value. Wherein, does not allow duplicate key object, and the value of the object may be repeated, and the value of the object may also be of type Map, Map interface to achieve two main categories: HashMap TreeMap class and classes. Wherein, according to the HashMap class key to access the object hash algorithm, and the TreeMap class objects can be sorted key

Map interface common method provided

V get(Object key)   返回 Map 集合中指定键对象所对应的值。V 表示值的数据类型
V put(K key, V value)   向 Map 集合中添加键-值对,返回 key 以前对应的 value,如果没有, 则返回 null
V remove(Object key)    从 Map 集合中删除 key 对应的键-值对,返回 key 对应的 value,如 果没有,则返回null
Set entrySet()  返回 Map 集合中所有键-值对的 Set 集合,此 Set 集合中元素的数据 类型为 Map.Entry
Set keySet()    返回 Map 集合中所有键对象的 Set 集合
Map map=new HashMap();
map.put("1","HelloWorld");
map.put("2","HelloWorld");

Collection class

Collections class provides a set of operations a number of static methods, static methods may be implemented by means of which the ordered set of elements, and replication filling operations

Forward Sorting

sort () methods are mainly the following two overloaded forms.

void sort(List list):根据元素的自然顺序对集合中的元素进行升序排序。
void sort(List list,Comparator comparator):按 comparator 参数指定的排序方式对集合中的元素进行排序。

List test=new ArrayList();
test.add(2);
test.add(1);
test.add(3);
Collections.sort(test); //此时数组为1,2,3

In reverse order

Calls reverse () static method can be carried out in reverse order of the elements in the specified collection

void reverse(List list)    //对集合中的元素进行反转排序

List test=new ArrayList();
test.add(2);
test.add(1);
test.add(3);
Collections.reverse(test); //此时数组为3,2,1

copy

copy Collections class () static method used to copy all of the specified elements in the collection to another collection

void copy(List <? super T> dest,List<? extends T> src)

List srcList=new ArrayList();
destList.add("1");
destList.add("2");
List destList=new ArrayList();
Collections.copy(destList,srcList);//此时destList为1,2

filling

fill Collections class () static methods of the specified set of the filling operation of all of the elements

void fill(List<? super T> list,T obj)    //使用指定元素替换指定列表中的所有元素

List test=new ArrayList();
test.add("1");
test.add("2");
Collections.fill(srcList,"0"); //此时List里全是0

Generics

Generics can be checked at compile time type safety, and all the cast are automatic and implicit, improve code reuse.

Generic collections

It is to provide the type of "type parameters" on generic in nature, that is, parameterized types. We, the interface or method is specified as a class type parameter, the data type of the operation limit of this parameter, so as to guarantee the absolute security of the type of conversion.

public class Person{
     private String name;
     public Person(String _name)
    {
        this.name=_name;
    }
}
Map<Integer, Person> persons=new HashMap<Integer, Person>();    //定义泛型 Map 集合
persons.add(new Person("HelloWorld"));

Map <Integer, Person> persons = new HashMap <Integer, Person> (); "creates a generic collection of key type Integer, Value type Person, existing of the key set stored in the Map must be of type Integer The value must be Person type, or compiler errors.

Person preson = persons.get(0);//在获取 Map 集合中的元素时,不需要将"persons.get(id);"获取的值强制转换为 Person 类型,程序会隐式转换

Generic class

In addition to define a generic collection, but also directly define the generic class type parameter.

public class class_name<data_type1,data_type2,…>{}
//泛型类一般用于类中的属性类型不确定的情况下。
private data_type1 property_name1;

When generic class instance, the generic parameters need to specify the type of class, and assigned a value corresponding to the type attribute of the generic class

public class Person<T>{
    private T param;
    public T getParam(){
        return param;
   }
   public void setParam(T _param){
        this. param = _param;
   }
}
public class Employee{
    //类型体
}
public static void main(String[] args){
    //约束为整形
    Person<Integer> intergerPerson = new Person<Integer>();
    intergerPerson. setParam(1);
    //约束为字符串类型
    Person<String> intergerPerson1 = new Person<String>();
    intergerPerson1. setParam("String");
    //除基础类型外,也可以约束为自定义类型
    Person<Employee> intergerPerson2 = new Person<Employee>();
    intergerPerson1. setParam(new Employee());
}

Generic class type parameter may have a plurality of

public class Person<T,N,S>{
    //使用同上
}

Generic method

It may be also included in the generic class of parametric methods, whereas the method may be where the generic class, may not be generic class.
Generic method such that the method can be generated independently of the class changes. If a generic method of the generic type which may be substituted, it should be used only a generic method. In addition, for a static method can not access the type parameter of a generic class. Therefore, if the static method requires the use of generic capabilities, we must make it a generic method.

[访问权限修饰符][static][final]<类型参数列表>返回值类型方法名([形式参数列表])
public static<T> void Test(T t){
}
String helloWorld = "HelloWorld";
Test("HelloWorld");

Guess you like

Origin www.cnblogs.com/lilinfeng/p/10995750.html