JavaSE learning notes - Collections, Arrays, other classes

Keywords: Java Attribute less

Java learning notes


Link: jdk13_API.

Tools

Collections

Collection and Collections

The difference between Collection and Collections:
Collection is the parent interface of Set and List collection, which provides a collection framework;
Collections is a tool class of operation collection, which provides many static methods of operation collection.

method

  • sort​(List< T > list)
  • sort​(List< T > list, Comparator<? super T> c)
  • max​(Collection<? extends T> coll)
  • max​(Collection<? extends T> coll, Comparator<? super T> comp)
  • min​(Collection<? extends T> coll)
  • min​(Collection<? extends T> coll, Comparator<? super T> comp)
  • binarySearch​(List<? extends Comparable<? super T>> list, T key)
  • binarySearch​(List<? extends T> list, T key, Comparator<? super T> c)
  • fill​(List<? super T> list, T obj)
  • replaceAll​(List< T > list, T oldVal, T newVal)
  • reverse​(List<?> list)
  • reverseOrder()
  • reverseOrder​(Comparator< T > cmp)
  • shuffle​(List<?> list)

Example

package collections;

import java.util.*;
/**
 * sort​(List<T> list)
 * sort​(List<T> list, Comparator<? super T> c)	
 * max​(Collection<? extends T> coll)
 * max​(Collection<? extends T> coll, Comparator<? super T> comp)
 * min​(Collection<? extends T> coll)
 * min​(Collection<? extends T> coll, Comparator<? super T> comp)
 * binarySearch​(List<? extends Comparable<? super T>> list, T key)
 * binarySearch​(List<? extends T> list, T key, Comparator<? super T> c)	
 * fill​(List<? super T> list, T obj)
 * replaceAll​(List<T> list, T oldVal, T newVal)
 * reverse​(List<?> list)
 * reverseOrder()
 * reverseOrder​(Comparator<T> cmp)
 * shuffle​(List<?> list)
 * 
 * @author 14251
 *
 */
class Comp implements Comparator<String>{
	@Override
	//Sort by string length
	public int compare(String o1, String o2) {
		Integer s1 = o1.length();
		Integer s2 = o2.length();
		int num = s1.compareTo(s2);
		if(num == 0) {
			//Sort in natural order when the length is the same
			return o1.compareTo(o2);
		}
		return num;
	}
}

public class CollectionsDemo {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("ac");
		list.add("aac");
		list.add("cdsx");
		list.add("devpp");
		list.add("e");
		
		/*
		//sort
		print(list);//ac, aac, cdsx, devpp, e
		Collections.sort(list);//sort
		print(list);//aac, ac, cdsx, devpp, e
		Collections.sort(list, new Comp());
		print(list);//e, ac, aac, cdsx, devpp
		*/
		
		/*
		//max
		String str1 = Collections.max(list);
		System.out.println(str1);//e
		String str2 = Collections.max(list, new Comp());
		System.out.println(str2);//devpp
		*/
		
		/*
		//binarySearch
		//First, make sure that the list is in order (the order here is not the order of list storage), then use binary search
		//If the element exists, return the element location; if the element does not exist, return: - the location - 1 should be inserted
		//1. The element implements the compatible interface, and then uses binary search
		//2. Use comparator, then with parameter Collections.sort() sorting, then binary search with parameters
		//Natural order
		Collections.sort(list);
		System.out.println(list);//[aac, ac, cdsx, devpp, e]
		int pos1 = Collections.binarySearch(list, "aac");
		System.out.println(pos1);//0
		//String Sort by length
		Collections.sort(list, new Comp());
		System.out.println(list);
		int pos2 = Collections.binarySearch(list, "aac", new Comp());//[e, ac, aac, cdsx, devpp]
		System.out.println(pos2);//2
		//If the element does not exist, assume sorting by length
		int pos3 = Collections.binarySearch(list, "xyz", new Comp());//[e, ac, aac, cdsx, devpp]
		System.out.println(pos3);//-4, -(-4)-1=3
		*/
		
		/*
		//fill
		Collections.fill(list, "a");
		System.out.println(list);//[a, a, a, a, a]
		*/
		
		/*
		//replaceAll
		System.out.println(list);//[ac, aac, cdsx, devpp, e]
		Collections.replaceAll(list, "ac", "abc");//Replace all oldVal in the List with newVal
		System.out.println(list);//[abc, aac, cdsx, devpp, e]
		*/
		
		/*
		//reverse()
		System.out.println(list);//[ac, aac, cdsx, devpp, e]
		Collections.reverse(list);
		System.out.println(list);//[e, devpp, cdsx, aac, ac]
		*/
		
		
		//reverseOrder
		//Natural order
		Set<String> set_natural = new TreeSet<String>();
		set_natural.addAll(list);
		System.out.println(set_natural);//[aac, ac, cdsx, devpp, e]
		//Reverse natural order
		Set<String> set_natural_reverse = new TreeSet<String>(Collections.reverseOrder());
		set_natural_reverse.addAll(list);
		System.out.println(set_natural_reverse);//[e, devpp, cdsx, ac, aac]
		//Length sort
		Set<String> set_length = new TreeSet<String>(new Comp());
		set_length.addAll(list);
		System.out.println(set_length);//[e, ac, aac, cdsx, devpp]
		//Reverse length order
		Set<String> set_length_reverse = new TreeSet<String>(Collections.reverseOrder(new Comp()));
		set_length_reverse.addAll(list);
		System.out.println(set_length_reverse);//[devpp, cdsx, aac, ac, e]
		
	}
	//Iterative output
	public static <T> void print(List<T> list) {
		Iterator<T> it = list.iterator();
		String res = "";
		while(it.hasNext()) {//If there is an element after the current pointer
			T t = it.next();//Pointer moves backward one bit (p+1)
			if(t instanceof String) {
				String str = (String)t;
				if(it.hasNext()) {//After the backward pointer, there is an element (p+2), not the last element
					res += str+", ";
				}else {
					res += str;
				}
				
			}
		}
		System.out.println(res);
	}

}

Arrays

method

  • Binary search (object [] A, object key): binary search must ensure the array to be searched is in order
  • asList​(T… a) : array to list < T > Set
  • toArray() of Collection interface: convert Collection to array
  • Arrays.toString(String str): array converted to string

Example

1. Binary search

package collections;

import java.util.*;

/*
 * 	binarySearch​(Object[] a, Object key)
 */
class TestClass  /*implements Comparable<TestClass>*/{
	String name;
	TestClass(String name){
		this.name = name;
	}
	/*
	@Override
	public int compareTo(TestClass t) {
		return this.name.compareTo(t.name);
	}
	*/
}
class MyCompare implements Comparator<TestClass>{

	@Override
	public int compare(TestClass t1, TestClass t2) {
		return t1.name.compareTo(t2.name);
	}
	
}
public class ArraysBinarySearch {
	public static void main(String[] args) {
//		ArrayList<TestClass> list = new ArrayList<TestClass>();
//		list.add(new TestClass("bac"));
//		list.add(new TestClass("cba"));
//		list.add(new TestClass("abc"));
//		Collections.sort(list, new MyCompare());
		Set<TestClass> set = new TreeSet<TestClass>(new MyCompare());
		set.add(new TestClass("bac"));
		set.add(new TestClass("cba"));
		set.add(new TestClass("abc"));
//		Collections.binarySearch(list, new TestClass("cba"), new MyCompare());
		TestClass[] str = set.toArray(new TestClass[set.size()]);
		Arrays.sort(str, new MyCompare());
		int res = Arrays.binarySearch(str, new TestClass("cba"), new MyCompare());
		System.out.println(res);
		
		char[] ch = {'a', 'b', 'c'};
		for(char c : ch) {
			System.out.println(c);
		}
	}
}

2. Other methods

  • Static import:
    If a class contains all static members (properties and methods), it can be done through static import for the convenience of calling.
    Format: import static
  • After static import, you can directly write the method name to call the unique static method in the imported class. If some methods have the same name as the methods in the calling class, they cannot be abbreviated at this time. They must be called through the class name. Method name.
  • Import imports classes, and import static imports all static members of a class.
package collections;

import java.util.*;
//Static import
import static java.util.Arrays.*;
/**
 * Array to collection
 * asList​(T... a)
 * Set to array
 * Collection toArray() of interface
 * Array to string
 * Arrays.toString(String str)
 * 
 * Enhance for loop
 * 
 * @author 14251
 *
 */
public class ArrayDemo {
	public static void main(String[] args) {
		Integer[] arr = {1, 2, 3};
		List<Integer> list1 = Arrays.asList(arr);
		System.out.println(list1);//[1, 2, 3]
		
		int[] array = {1, 2, 3};
//		List<int[]> list2 = Arrays.asList(array);
		List<int[]> list2 = asList(array);//Static import
		System.out.println(list2);//[[I@52cc8049]
		
		List<String> list3 = new ArrayList<String>();
		list3.add("a");
		list3.add("b");
		list3.add("c");
		//Method 1
		Object[] obj = list3.toArray();
		System.out.println(Arrays.toString(obj));////[a, b, c]
//		for(Object o : obj) {
//			String str = (String)o;
//			System.out.print(str + " ");//a b c 
//		}
//		System.out.println();
		//Method 2
//		String[] str = list3.toArray(new String[0]);
//		System.out.println(Arrays.toString(str));//[a, b, c]
		
//		String[] str = list3.toArray(new String[4]);
//		System.out.println(Arrays.toString(str));//[a, b, c, null]
		
		String[] str = list3.toArray(new String[list3.size()]);
		System.out.println(Arrays.toString(str));//[a, b, c], can't use ToString
												 //Because the Object class also has this method, which is not unique to Arrays
		
		HashMap<Integer, String> hm = new HashMap<Integer, String>();
		hm.put(1, "a");
		hm.put(2, "b");
		hm.put(3, "c");
		for(Map.Entry<Integer, String> me : hm.entrySet()) {
			System.out.println(me.getKey()+ " " + me.getValue());
			/*
			 * 1 a
			 * 2 b
			 * 3 c
			 */
		}
		for(Integer i : hm.keySet()) {
			System.out.println(i + " " + hm.get(i));
		}
	}
}

analysis

1. What's the advantage of converting an array to a List set?

  • You can use the idea of a collection to manipulate elements in an array.

2. What's the advantage of converting a set to an array?

  • In order to restrict the operation of elements, you cannot add or delete arrays.

3. Public < T > t [] toArray (t [] a) method in collection interface:

  • This method in the collection framework can be used to directly specify the type of array to be converted, avoiding the trouble of no parameter toArray() method to cast, but what should be the length of the specified array?
    Assuming that there are three elements in the collection, when the length of the new array is [0, 3], the virtual machine will automatically save all elements in the exported array; if the length is greater than 3, the virtual machine will supplement the extra part with null. Therefore, it is best to set the length of the exported array to the length of the set, that is, set. size()

4. Precautions:

  • When an array is converted to a List set, you cannot use the add and delete methods in the set to operate the set, because the length of the array is fixed, so the length of the converted List set is also fixed. You can use judgment methods, such as contains(), get(), etc.
  • If the element in the array is of reference data type, when converting to a collection, each reference object in the array is treated as an element in the collection, so the generic type of the collection is reference data type T (such as list < string >); if the elements in the array are of basic data type, when converting to a collection, the array is stored as a whole in the collection, so the generic type of the collection is array [] (such as list < int []).

5. Advanced for loop

  • Format:

    For (data type variable name: the traversed Collection or array){
    	Operation of data;
    }
    
  • The enhanced for loop can only traverse the collection or array, simplifying the writing of iterator(), and cannot operate on the collection element itself.

  • In addition to traversing the collection, iterator() can also remove() the elements in the collection.

  • List iterator () can add, delete, modify and query the elements in the list collection while traversing the list collection.

  • The premise of advanced for recycling is that there must be traversal targets.

  • It is recommended to use the traditional for loop when traversing an array, because you can use the subscript to operate on the elements in the array.

Others

Date class

package otherClass;

import java.text.SimpleDateFormat;
import java.util.*;

public class DateDemo {
	public static void main(String[] args) {
		Date date = new Date();
		System.out.println(date);//Thu Jun 18 16:49:07 CST 2020
		//Print result of Date object is not easy to view
		//Using the SimpleDataFormat class to format the printed results
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day E hh:mm:ss");//Incoming format
		String str = sdf.format(date);//Call the format() method and pass in the Date object
		System.out.println(str);//Thursday, June 18, 2020 04:49:07
	}
}

Calendar Class

package otherClass;

import java.util.Calendar;

public class CalendarDemo {
	public static void main(String[] args) {
		//The Calendar class cannot create an object, it can only get an object through a method
		Calendar cal = Calendar.getInstance();
		//public int get (int field), field is the constant value provided in the Calendar class
		String year = cal.get(Calendar.YEAR) + "year";
		String month = cal.get(Calendar.MONTH) + "month";
		String day = cal.get(Calendar.DAY_OF_MONTH) + "day";
		String week = "week" + cal.get(Calendar.DAY_OF_WEEK);
		System.out.println(year + month + day + week);//Friday, May 18, 2020 (June 18, 2020-4)
		
		//Month starts from 0, week starts from Sunday, so redefine month and week
		System.out.println(getTime(cal));//Thursday, June 18, 2020
		
		//Key add(int field, int amount) - (attribute, offset)
		cal.add(Calendar.YEAR, 2);
		System.out.println(cal.get(Calendar.YEAR));//2022
		cal.add(Calendar.DAY_OF_MONTH, -20);
		System.out.println(getTime(cal));//May 29, 2022
	}
	//Get time
	public static String getTime(Calendar c) {
		//Get the corresponding month by looking up the table
		String[] Month = {
				"1 month", "2 month", "3 month", "4 month", 
				"5 month", "6 month", "7 month", "8 month", 
				"9 month", "10 month", "11 month", "12 month"
		};
		String[] Week = {
				"", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
		};
		int year = c.get(Calendar.YEAR);
		String month = Month[c.get(Calendar.MONTH)];
		int day = c.get(Calendar.DAY_OF_MONTH);
		String week = Week[c.get(Calendar.DAY_OF_WEEK)];
		return year+"year"+month+day+"day"+" "+week;
	}
}

practice

  1. Get the number of days in February of any year.
  2. Get the present moment of yesterday.
package otherClass;

import java.util.Calendar;

public class GetDayDemo {
	public static void main(String[] args) {
		System.out.println(getFebDay(2020));
		System.out.println(getTime());
	}
	//Get the number of days in February of any year
	public static int getFebDay(int year) {
		Calendar c = Calendar.getInstance();
		c.set(year, 2, 1);//Date set to March 1 of a year
		c.add(Calendar.DAY_OF_MONTH, -1);//March 1 is the last day of February
		return c.get(Calendar.DAY_OF_MONTH);
	}
	//Get the present moment of yesterday
	public static String getTime() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, -1);//One day back today is the present moment of yesterday
		return c.get(Calendar.MONTH)+"month"+c.get(Calendar.DAY_OF_MONTH)+"day"
				+c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);
	}
}

Math class

package otherClass;

import java.util.Random;
/*
 * Math Some methods in class
 */
public class MathDemo {
	public static void main(String[] args) {
		//1. Power
		double p = Math.pow(2, 3);
		System.out.println(p);//8.0
		
		//2. Rounding
		double r = Math.round(3.14);
		System.out.println(r);//3.0
		
		//3. Round up, the smallest integer greater than x
		double c = Math.ceil(6.28);
		System.out.println(c);//7.0
		
		//4. Round down, the largest integer less than x
		double f = Math.floor(12.56);
		System.out.println(f);//12.0
		
		//5. Random number
		for(int i=0; i<10; i++) {
			System.out.println(Math.random());//Random number of output [0-1]
			/*
			0.2605054528905104
			0.49246740134864964
			0.23014167966383436
			0.347073370214814
			0.2976473426537575
			0.3119785239575279
			0.3296263971497272
			0.31950953896042156
			0.6131484251716923
			0.5133107128932459
			*/
			System.out.println((int)(Math.random()*10+1));//Random number of output [1-10]
			System.out.println((int)(Math.random()*6+1));//Output [1-6] random number (dice)
		}
		
		//Random number generation is also provided in random class
		//nextInt() returns an int type random number, nextInt(int bound) returns an int type random number within [0, bound]
		Random rand = new Random();
		for(int i=0; i<10; i++) {
			int r1 = rand.nextInt(10)+1;//Generate random number of [1-10]
			System.out.println(r1);
		}
	}
}

Posted by JackOfBlades on Fri, 19 Jun 2020 03:57:27 -0700