当前位置:网站首页>Collection collection and map collection

Collection collection and map collection

2022-07-06 15:10:00 Hand pluckable Xinchen

1,Collection aggregate

        Collection<E>: Single column set ( Interface )

        List<E>( Interface ):

         characteristic :

                1, There are index values

                2, Can be repeated

                3, Arrange in order

        List<E> Member methods in interfaces :

                void add(int index,E e);

                E remove(int index);

                E get(int index);

                E set(int index,E e);

                List<E> subList(int beginIndex,int endIndex);

                int indexOf(Object o);

                int lastIndexOf(Object o);

public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("aa");
		list.add("bb");
		list.add("cc");
		list.add("dd");
		list.add("ee");		
		list.add(0, "aaa");
		System.out.println(list);
		String removeElement = list.remove(0);
		System.out.println(" The deleted element is :"+removeElement);// The deleted element is :aaa
		System.out.println(list);
		String element = list.get(0);
		System.out.println(element);//aa		
		String replaceElement = list.set(0, "aaa");
		System.out.println(" The element to be replaced is :"+replaceElement);// The element to be replaced is :aa
		System.out.println(list);		
		List<String> list2 = list.subList(1, 3);// Left closed right away 
		System.out.println(list2);		
	}

         Implementation class :

                ArrayList( The underlying implementation is an array )

                        characteristic : Quick query , Add or delete slowly

                LinkedList( The underlying implementation is the linked list )       

                        characteristic : Slow query , Additions and deletions quickly

                LinkedList<E> Class unique member methods :

                        void addFirst(E e);

                        void addLast(E e);

                        String removeFirst();

                        String removeLast();

                        String getFirst();      

                        String getLast();

public static void main(String[] args) {
		LinkedList<String> list = new LinkedList<>();
		list.add("aa");
		list.add("bb");
		list.add("cc");
		list.add("dd");
		list.add("ee");
		
		list.addFirst("aaa");
		list.addLast("eee");
		System.out.println(list);
		
		String first = list.removeFirst();
		System.out.println(first);//aaa
		String last = list.removeLast();
		System.out.println(last);//eee
		System.out.println(list);
		
		first = list.getFirst();
		System.out.println(first);//aa
		last = list.getLast();
		System.out.println(last);//ee		
		
	}

        Set( Interface ):

         characteristic :

                1, No index value

                2, Can't repeat

        Implementation class :

                TreeSet( At the bottom are red and black trees , Sortable )

                Be careful :TreeSet When adding new elements , Generics must be Comparable type

                        Construction method :

                             public TreeSet();

                             public TreeSet(Comparator<> c);           

public class Test06 {
	public static void main(String[] args) {
		//TreeSet When adding new elements , Generics must be Comparable type 
		Set<Person> set = new TreeSet<>();
		set.add(new Person(" Zhang San "));
		set.add(new Person(" Zhang San is crazy "));
		set.add(new Person(" Zhangsanxiao "));
		System.out.println(set);
	}
}

class Person implements Comparable<Person>{
	private String name;
	public Person(String name) {
		super();
		this.name = name;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + "]";
	}
	  	// Mainly speaking of the rules of comparison 
	  		// Ascending : The current object - Parameter object 
	  		// Descending : Parameter object - The current object 	 
	@Override
	public int compareTo(Person o) {
		// Ascending 
		int result = this.name.length()-o.name.length();		
	}
}

public class Test07 {
	public static void main(String[] args) {		
		// establish Comparator Object of type 
		Comparator<Teacher> c = new Comparator<Teacher>() {
			@Override
			public int compare(Teacher t1, Teacher t2) {				
				  //	 Ascending :
				  //		 Parameters 1- Parameters 2
				  //	 Descending :
				  //		 Parameters 2- Parameters 1				 
				int result = t2.getName().length()-t1.getName().length();
				return result;
			}
		};		
		Set<Teacher> set = new TreeSet<>(c);
		set.add(new Teacher(" Zhang San "));
		set.add(new Teacher(" Zhang San is crazy "));
		set.add(new Teacher(" Zhangsanxiao "));
		System.out.println(set);
	}
}

class Teacher{
	private String name;	
	public String getName() {
		return name;
	}
	public Teacher(String name) {
		super();
		this.name = name;
	}
	@Override
	public String toString() {
		return "Teacher [name=" + name + "]";
	}
}

                HashSet( At the bottom is the hash table , disorder )

                         Hashtable : Array + Linked list + Red and black trees

                Be careful : If an object of a custom type , We want to add to HashSet Collection , We think that the values of member variables are the same , It's the same element , You need to overwrite hashCode Methods and equals Method .

                LinkedHashSet( At the bottom is the list + Hashtable , Orderly )

2,Collection The common method of collection      

boolean add(E e);      Add an element
boolean addAll(E e);    Add multiple elements
boolean isEmpty(); Determines if the set is empty
boolean contains(E e); Find out if the element exists
boolean containsAll(E e); Find out if multiple elements exist
boolean remove(E e); Delete the element
boolean removeAll(E e); Delete multiple elements
int size(); The number of set elements
void clear(); Empty the set

Object[] toArray();

Convert collection to array
Iterator<E> iterator(); Return to one Iterator object , Used to traverse collections

3,Iterator iterator

(1) Get iterator object

        Iterator i = A collection of objects .iterator();

(2) Determine if there is the next element

        i.hasNext();

(3) Get elements

        i.next();

public static void main(String[] args) {
		Collection<String> c = new ArrayList<>();
		c.add(" Zhang San ");
		c.add(" Li Si ");
		c.add(" Wang Wu ");		
		// Get iterator object 
		Iterator<String> iterator = c.iterator();
		while(iterator.hasNext()) {
			String element = iterator.next();
			System.out.println(element);
	}

4, enhance for loop

Introduce : enhance for At the bottom of the loop is the iterator . Can traverse a set 、 Array .

        Format :

                for( Data type of array / Generics of sets Variable name : The set to traverse / Array ){

                        System.out.println( Variable name );

                }

5,Collections class        

 static <T> boolean addAll(Collection<T> c,T... array); Add multiple elements to the collection
static  void sort(List<> list); Sort the set in ascending order
static <T extends Comparable<T>> void sort(List<T> list); Set according to Comparable The methods in the interface are sorted
static <T> void sort(List<T> list,Comparator<T> c); Set according to Comparator The methods in the interface are sorted
static void shuffle(List<?> list); Sort the set out of order

Collections.reverse(List<T> list);

Sort the set in reverse

6,Map aggregate

        Map<K,V>: Dual column set interface

        characteristic :

                (1) An element has a K, One V Two parts .

                (2)K  V It can be any reference data type .

                (3) One K Corresponding to the only one V.K Can't repeat .

        Common implementation classes :

                HashMap implements Map

                         Bottom : Hashtable

                         characteristic : The order of adding and removing is not necessarily the same ( disorder )

                LinkedHashMap extends HashMap

                         Bottom : Hashtable + Linked list

                         characteristic : The order of adding is the same as that of taking out ( Orderly )

                TreeMap

                        Bottom : Red and black trees ( Sortable )

                Hashtable: Thread safety , Low efficiency

                HashMap: Thread unsafe , Efficient

        Common methods :

V put(K k,V v);

If K There is , It's new V Replace old V, Returns the replaced V.

If K non-existent , Then return to null.

V remove(Object key);

Remove elements , according to key Delete the entire element , Returns the of the deleted element V.

If Key non-existent , Then return to null.

V get(Object key); according to key obtain V, If key Returns if it does not exist null.
boolean containsKey(Object key);

If K There is , return true.

If K non-existent , return false.

boolean containsValue(Object value);

If V There is , return true.

If V non-existent , return false.

boolean isEmpty(); Determines if the set is empty .
void clear(); Empty the set
int size(); Get the number of elements in the collection

         Case study : Convert a two column set to a single column set

public static void main(String[] args) {
		Map<String,Double> map = new HashMap<>();
		map.put(" Zhang San ", 90.0);
		map.put(" Zhang Sanfeng ", 99.0);
		map.put(" Zhang San is crazy ", 90.0);		
		  // hold Map Convert a two column set to a single column set 		 
		// Get all V
		Collection<Double> values =  map.values();
		System.out.println(values);
		// Get all K
		Set<String> set = map.keySet();
		System.out.println(set);
		for(String key:set) {
			// according to key obtain V
			Double v = map.get(key);
			System.out.println(key+"--"+v);
		}
	}

        Entry<K,V> Interface :

                K getKey();
                V getValue();

public static void main(String[] args) {
		Map<String,Double> map = new HashMap<>();
		map.put(" Zhang San ", 90.0);
		map.put(" Zhang Sanfeng ", 99.0);
		map.put(" Zhang San is crazy ", 90.0);
		// Get all Entry
		Set<Entry<String,Double>> entrySet =  map.entrySet();
		Iterator<Entry<String,Double>> iterator = entrySet.iterator();
		while(iterator.hasNext()) {
			Entry<String,Double> entry = iterator.next();
			String key = entry.getKey();
			Double value = entry.getValue();
			System.out.println(key+"--"+value);
		}
	}

7, Variable parameters

         Definition :

                 Method name ( data type ... Variable name );   

         matters needing attention :

                1. A method can only have one variable parameter
                2. If you have more than one parameter , The variable parameter must be the last
       

public static void main(String[] args) {
		int[] array = {10,20,30,40,50};
		method(array);		
//		method(1,2,3,4,5);//1,2,3,4,5		
//		method();//0
	}	
	public static void method(int... nums) {
		System.out.println(nums.length);
		// Let's treat variable parameters as arrays 
		for (int i = 0; i < nums.length; i++) {
			System.out.println(nums[i]);
		}
	}

        

                                        

                               

                

原网站

版权声明
本文为[Hand pluckable Xinchen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060919160415.html