Java summary container [easy to understand]

Posted by silverphpd on Tue, 25 Jan 2022 14:40:08 +0100

Hello, everyone. Meet again. I'm Jun Quan.

[concept of container] Container: a series of instances provided by Java API for storing objects in programs. [container API] The container API provided by J2SDK is located in Java Util package.

 {Collection[Set(HashSet,LinkedList),SrrayList]}{Map[HashMap]}

Collection interface – defines the method of accessing a group of objects, and its sub interfaces Set and List define the storage method respectively.

The data objects in the Set have no order and cannot be repeated The data objects in the List are sequential and repeatable The Map interface defines a method for storing "key value mapping pairs". [Collection interface] Methods defined in the Collection interface:

int size();
 boolean isEmpty();
 void clear();
 boolean contains(Object element);
 boolean add(Object element);
 boolean remove(Object element);
 Iterator iterator();
 boolean containsAll(Collection c);
 boolean addAll(Collection c);
 boolean removeAll(Collection c);
 boolean retainAll(Collection c);
 Object[] toArray();
 

When a container class object calls methods such as remove and contains, it is necessary to compare whether the objects are equal, which involves the equals method and hashCode method of the object type. For self-defined types, you need to override the equals and hashCode methods to implement the self-defined object equality rules. Note: equal objects should have equal hash codes.

Add the equals and hashCode methods of the Name class, for example:

public boolean equals(Object obj) {
	if(obj instanceof Name) {
		Name name = (Name) obj;
		return (firstName.equals(name.firstName))
			&& (lastNmae.equals(name.lastName));
	}
	return super.equals(obj);
}
public int hashCode() {
	return firstName.hashCode();
}

[Iterator interface] All container classes that implement the Collection interface have an iterator method to return an object that implements the iterator interface. The Iterator object is called an Iterator to facilitate the traversal of elements in the container. The Iterator interface defines, for example, the following methods:

boolean hasNext(); //Infer whether there is an element on the right side of the cursor
 
 Object next(); //Returns the element to the right of the cursor and moves the cursor to the next position
 
 void ermove(); //Deletes the element to the left of the cursor. After running next, the operation can only be run once

The remove method of the Iterator object is the only safe way to remove elements during the iteration. [JDK1.5 enhanced for loop] example:

import java.util.*;
public class EnhancedFor {
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5};
		for(int i:arr) {
			System.out.println(i);
		}
		
		Collection<String> c = new ArrayList<String>();
		c.add(new String("aaa"));
		c.add(new String("bbb"));
		c.add(new String("ccc"));
		for(Object o : c) {
			System.out.println(o);
		}
	}
}

Note: java1 Generics were used after 5. (for example, < string > specifies the type of element stored in the container) The enhanced for loop is quite simple for traversing array or Collection Defects: Array: Cannot easily access subscript values Set: Compared with using Iterator, it is not convenient to delete the content in the collection Internally, Iterator is also called Summary: enhanced for is not recommended except for simple traversal and readout [Set interface] The Set interface is a sub interface of the Collection. The Set interface does not provide additional methods. However, the elements in the container class that implements the Set interface are out of order. And can not be repeated. The Set container can correspond to the concept of "Set" in mathematics. The Set container classes provided in J2SDK API include HashSet, TreeSet, etc. [Set method example]

import java.util.*;
public class Test {
	public static void main(String[] args) {
		Set<String> s1 = new HashSet<String>();
		Set<String> s2 = new HashSet<String>();
		s1.add("a");s1.add("b");s1.add("c");
		s2.add("d");s2.add("a");s2.add("b");
		//Both the Set and List container classes have a Constructor(Collection c)
		//Constructor is used to initialize the container class
		Set<String> sn = new HashSet<String>(s1);
		sn.retainAll(s2);
		Set<String> su = new HashSet<String>(s1);
		su.addAll(s2);
		System.out.println(sn);
		System.out.println(su);
	}
}

[List interface] The List interface is a sub interface of the Collection. The elements in the container class that implements the List interface are sequential and can be repeated.

The elements in the List container correspond to an integer serial number to record their position in the container. The elements in the container can be accessed according to the sequence number. The List container classes provided by J2SDK include ArrayList,LinkedList, etc.

Object get(int index);
 Object set(int index,Object element);
 void add(int index,Object element);
 Object remove(int index);
 int indexOf(Object o);
 int lastIndexOf(Object o);
 

[List often uses algorithms] Class java util. Collections provides some static methods and implements some commonly used algorithms based on the List container. void sort(List) sorts the elements in the List container void shuffle(List) randomly sorts the objects in the List container void fill(List,Object) rewrites the entire List container with a specific object void copy(List dest,List src) copies the contents of the src List container to the dest List container int binarySearch(List,Object) for sequential List containers, use this search method to find specific objects [List often uses algorithm examples]

import java.util.*;
public class Test {
	public static void main(String[] args) {
		List<String> l1 = new LinkedList<String>();
		List<String> l2 = new LinkedList<String>();
		for(int i=0;i<=9;i++) { l1.add("a"+i); }
		System.out.println(l1);
		Collections.shuffle(l1); //Random sorting
		System.out.println(l1);
		Collections.reverse(l1); //Reverse order
		System.out.println(l1);
		Collections.sort(l1); //sort
		System.out.println(l1);
		System.out.println(Collections.binarySearch(l1,"a5")); //Half search
	}
}

[Comparable interface] Question: on what basis does the above algorithm determine the "size" order of objects in the container? All classes that can "sort" implement Java Lang. Comparable interface. There is only one method in the Comparable interface public int CompareTo(Object obj); This method:

Return 0 to indicate this == obj
 
  Returns a positive number representation this > obj
 
  Returns a negative number representation this < obj
 
 

The class that implements the Comparable interface determines the sorting mode of this class of objects by implementing the compareTo method. [how to select data structure] Measurement criteria: reading efficiency and correction efficiency The Array is almost full Linked fast Duman Hash between the two [Map interface] The class that implements the Map interface is used to store key value pairs. The implementation classes of Map interface include HashMap and TreeMap.

The key value pairs stored in the Map class are identified by creation, so the key value cannot be repeated.

Object put(Object key,Object value);
 Object get(Object key);
 Object remove(Object key);
 boolean containsKey(Object key);
 boolean containsValue(Object value);
 int size();
 boolean isEmpty();
 void putAll(Map t);
 void clear();
 

[example of Map method]

import java.util.*;
public class Test {
	public static void main(String[] args) {
		Map<String,Integer> m1 = new HashMap<String,Integer>(); 
		Map<String,Integer> m2 = new TreeMap<String,Integer>();
		m1.put("one" , new Integer(1));
		m1.put("two" , new Integer(2));
		m1.put("three" , new Integer(3));
		m1.put("A" , new Integer(1));
		m2.put("B" , new Integer(2));
		System.out.println(m1.size());
		System.out.println(m1.containsKey("one"));
		System.out.println(m2.containsValue(new Integer(1)));
		if(m1.containsKey("two")) {
			int i = ((Integer)m1.get("two")).intValue();
			System.out.println(i);
		}
		Map<String,Integer> m3 = new HashMap<String,Integer>(m1);
		m3.putAll(m2);
		System.out.println(m3);
	}
}

[Auto-boxing/unboxing] Take the initiative to pack and Jaguar at the right time Actively convert the base type to an object Actively convert the object to the base type [JDK1.5 generic] Cause:   JDK1.4. I don't understand: The types of loaded collections are treated as objects. Thus losing their actual type.

When taking out from the set, it often needs transformation, which is inefficient and easy produces errors.

Solution: When defining a collection, the types of objects in the collection are defined at the same time Specify when you can redefine the Collection It can also be specified with iterator when looping Advantages: enhance the readability and stability of the program. [summary] A graph; A class Collections; Three knowledge points: for, generic, auto boxing / unboxing; Six interfaces

Publisher: full stack programmer, stack length, please indicate the source for Reprint: https://javaforall.cn/116255.html Original link: https://javaforall.cn