The comparator

package aaa;

import java.util.Comparator;

public class ComparatorByLength implements Comparator {

     public int compare(String o1, String o2) {

              String s1 = (String) o1;

              String s2 = (String) o2;

              int temp = s1.length() - s2.length();

              return temp == 0 ? s1.compareTo(s2) : temp;

     }
Copy the code

}

package aaa;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

import java.util.TreeSet;

public class ListDemo {

public static void main(String[] args) { // TODO Auto-generated method stub demo_1(); demo_2(); demo_3(); Demo4(); } public static void Demo4() { List<String> list = new ArrayList<String>(); list.add("abcde"); list.add("cba"); list.add("zhangsan"); list.add("zhaoliu"); list.add("xiaoqiang"); System.out.println(list); Collections.replaceAll(list, "cba", "NBA"); / / principle set (indexOf (" cba "), "NBA"); System.out.println(list); Collections.shuffle(list); // Replaces the specified list with the specified random source. System.out.println(list); Collections.fill(list, "cc"); // Replace all elements in the list with cc. This method is used to initialize the collection system.out.println (list); } public static void demo_3() {TreeSet<String> ts = new TreeSet<String>(new Comparator<String>() { @Override public int compare(String o1, String o2) { int temp = o2.compareTo(o1); return temp; }}); ts.add("abc"); ts.add("hahaha"); ts.add("zzz"); ts.add("aa"); ts.add("cba"); System.out.println(ts); // Use the method in the utility class to reverse sort, sort by comparator. TreeSet<String> ts1 = new TreeSet<String>( Collections.reverseOrder(new ComparatorByLength())); ts1.add("abc"); ts1.add("hahaha"); ts1.add("zzz"); ts1.add("aa"); ts1.add("cba"); System.out.println(ts1); } public static void demo_1() {List<String> List = new ArrayList<String>();} public static void demo_1() {List<String> List = new ArrayList<String>(); list.add("abcde"); list.add("cba"); list.add("aa"); list.add("zzz"); list.add("cba"); list.add("nbaa"); System.out.println(list); Collections.sort(list); mySort(list); // collections.sort (list) system.out.println (list); Collections.sort(list, new ComparatorByLength()); mySort(list, new ComparatorByLength()); System.out.println(list); } public static <T> void mySort(List<T> list, Comparator<? super T> comp) { for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (comp.compare(list.get(i), list.get(j)) > 0) { Collections.swap(list, i, j); }}}} /** * @param list * collections.sort (list) implementation principle, T extends Comparable<? */ public static <T extends Comparable<? super T>> void mySort(List<T> list) { for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i).compareTo(list.get(j)) > 0) { Collections.swap(list, i, j); }}}} public static void demo_2() {List<String> List = new ArrayList<String>(); list.add("abcde"); list.add("cba"); list.add("aa"); list.add("zzz"); list.add("cba"); list.add("nbaa"); System.out.println(list); Collections.sort(list); int index = Collections.binarySearch(list, "cba"); System.out.println("index=" + index); String max = Collections.max(list, new ComparatorByLength()); System.out.println("max=" + max); }Copy the code

}

The Java.util. Arrays class makes it easy to manipulate Arrays, and all the methods it provides are static. It has the following functions:

To assign an array: use the fill method. Sort arrays: By sort method, in ascending order. Compare arrays: Compares the values of the elements in an array using equals. Find array elements: binarySearch can be used to find sorted arrays. import java.util.Arrays;

public class TestArrays {

public static void output(int[] array) {

if (array! =null) {

for (int i = 0; i < array.length; i++) {

System.out.print(array[i]+” “);

}

}

System.out.println();

}

public static void main(String[] args) {

int[] array = new int[5];

// Populate the array

Arrays.fill(array, 5);

System.out.println(” Array.fill (array, 5) : “);

TestArrays.output(array);

// Assign the 2nd and 3rd elements of the array to 8

Arrays.fill(array, 2, 4, 8);

System.out.println(” Array.fill (array, 2, 4, 8) : “);

TestArrays.output(array);

7,8,3,2,12,6,3,5,4 int [] array1 = {};

// Sort the array from 2 to 6

The Arrays. Sort (array1, 2, 7);

System.out.println(” Sort from array. Sort (array,2,7) : “);

TestArrays.output(array1);

// Sort the entire array

Arrays.sort(array1);

System.out.println(” Array.sort (array1) : “);

TestArrays.output(array1);

// Compare array elements for equality

System.out.println(” Compares Arrays. Equals (array, array1):”+”\n”+ array.equals (array, array1));

int[] array2 = array1.clone();

System.out.println(” Array. equals(array1, array2):”+”\n”+ array. equals(array1, array2));

// Use binary search algorithm to find the subscript of the specified element (must be sorted, otherwise the result is incorrect)

Arrays.sort(array1);

Array. BinarySearch (array1, 3) : “+”\n”+ Array. binarySearch(array1, 3));

// Return a negative number if it does not exist

Array1: “+”\n”+Arrays. BinarySearch (array1, 9));

}

}

Output result:

Fill (array, 2, 4, 8) : 5 array. Fill (array, 2, 4, 8) : 5 array. Array.sort (array,2,7) : 7 8 2 3 3 6 12 5 4 Array. equals(array, array1): Array. equals(array1, array2):true Location of element 3 in array1: binarySearch(array1, 3) : 1 location of element 9 in array1: Arrays. BinarySearch (array1, 9) : – 9

Convert array to List collection package AAA;

import java.util.Arrays;

import java.util.List;

public class ArraysDemo { public static void main(String[] args) { demo_1();

       demo_2();
Copy the code

}

/ * *

The * arrays. asList method converts an array to a List collection */Copy the code

public static void demo_1()

{/ *

* key: List asList converts an array to a collection. * Benefits: You can actually use collection methods to manipulate elements in arrays. * note: the length of the array is fixed, so the methods to add or delete collection is not can use * otherwise occur UnsupportedOperationException * / String [] arrStrings = {" ABC ", "haha", "xixi"}; List<String> list=Arrays.asList(arrStrings); boolean b1=list.contains("xixi"); //list.add("hehe"); //UnsupportedOperationException System.out.println("list contains="+b1);Copy the code

}

public static void demo_2()

{ /*

* If an array element is an object, then the array element is stored as an element in the collection when converted to a collection.Copy the code
  • If the elements in the array are primitive-type values, the array is stored as an element in the collection.

    * / Integer [] arrIntegers =,32,434,55,67,87 {12}; // List<Integer> list=Arrays.asList(arrIntegers); System.out.println(list); / / output: [12, 32, 434, 55, 67, 87] int [] arr = {31,11,51,61}; List<int[]> list1=Arrays.asList(arr); System.out.println(list1.toString()); // Output result: [[I@154ab8e4]Copy the code

}

}

Collection to array package AAA;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class ToArray { public static void main(String[] args) { /*

* What about collections into arrays? * The toArray method in the Collection interface is used. Collection to array: You can qualify the methods by which elements in a collection can be manipulated. It is not allowed to add or delete. */ List<String> list = new ArrayList<String>(); list.add("abc1"); list.add("abc2"); list.add("abc3"); The toArray method requires passing in an array of the specified type. * How do I define length? * If the length is less than the size of the collection, this method creates an array of the same type and size as the collection. * If the length is greater than the size of the collection, then the method uses the specified array to store the elements of the collection, default to null elsewhere. * So it's recommended that the length be specified as the size of the set. */ String[] arrStrings=list.toArray(new String[list.size()]); System.out.println(Arrays.toString(arrStrings)); [abc1, abc2, abc3]Copy the code

}

}

1. Format:

For (type variables: set Collection | array)

{}Copy the code

Equivalent to foreach in C#

What is the difference between traditional for and advanced for?

Traditional for can execute the statement many times because you can define the increments and conditions for the control loop.

Advanced for is a simplified form.

It must have a target to traverse. The target is either an array or a Collection of single columns.

If traversal of a logarithmic array is just to get the elements of the array, advanced for can be used.

It is recommended to use traditional for if you want to operate on array markers.

package aaa;

import java.util.ArrayList;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

public class ForEachDemo {

public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("abc1"); list.add("abc2"); list.add("abc3"); For (String s:list) {// Simplify writing system.out.println (s); Arr =,3,3,4} {2} int []; for (int i :arr) { System.out.println(i); } Map<Integer, String> map=new LinkedHashMap<Integer,String>(); map.put(3, "zhangsan"); map.put(2,"wangyi"); map.put(7,"wangwu"); map.put(4, "zhangsansan"); for (Integer key:map.keySet()) { String valueString=map.get(key); System.out.println(key+"::"+valueString); } for(Map.Entry<Integer, String> me:map.entrySet()) { Integer keyInteger=me.getKey(); String valString=me.getValue(); System.out.println(keyInteger+":"+valString); }}Copy the code

}

Output result:

abc1

abc2

abc3

2

3

3

4

3::zhangsan

2::wangyi

7::wangwu

4::zhangsansan

3:zhangsan

2:wangyi

7:wangwu

4:zhangsansan

package cn.itcast.p4.news.demo;

public class ParamterDemo { /**

* @param args */ public static void main(String[] args) {int sum = newAdd(5,1,4,7,3); System.out.println("sum="+sum); Int sum1 = newAdd (5,1,2,7,3,9,8,7,6); System.out.println("sum1="+sum1); } /* * the variable argument to the function. * is actually an array, but receives the elements of the array. * Automatically encapsulate these elements into arrays. Simplifies writing for callers. * Note: Variable parameter types must be defined at the end of the parameter list. */ public static int newAdd(int a,int... arr){ int sum = 0; for (int i = 0; i < arr.length; i++) { sum+=arr[i]; } return sum; }Copy the code

package cn.itcast.p4.news.demo;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import static java.util.Collections.*; // Static import is a static member of the class.

import static java.lang.System.*;

public class StaticImportDemo { /**

* @param args */ public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("abc3"); list.add("abc7"); list.add("abc1"); out.println(list); sort(list); // After static import, you don't need to write Collections system.out.println (list); String max = max(list); System.out.println("max="+max); }Copy the code

}

Output result:

[abc1, abc3, abc7]

max=abc7

package aaa;

import java.util.Properties;

import java.util.Set;

public class SystemDemo { private static final String LINE_SEPARATOR = System

.getProperty("line.separator"); // Get the newline character. Different systems have different newlines. Public static void main(String[] args) {// TODO auto-generated method Stub Demo_1 (); demo_2(); } private static void demo_2() {/* * System: methods and attributes in a class are static. Long currentTimeMillis(); Gets the millisecond value of the current time. */ long l2 = System.currentTimeMillis(); System.out.println(l2); System.out.println("hello-"+LINE_SEPARATOR+" world"); Private static void demo_1() {private static void demo_1() {private static void demo_1() {private static void demo_1() {private static void demo_1() {private static void demo_1() { The /* * properties collection stores keys and values of String type. It is best to use its own store and fetch method to complete the operation of the element. */ Properties properties = System.getProperties(); Set<String> namSet = properties.stringPropertyNames(); for (String string : namSet) { String valueString = properties.getProperty(string); System.out.println(string + "::" + valueString); }}Copy the code

}

In Java, the Runtime class represents the Runtime operation class. It is a class that encapsulates the JVM process. Each JVM corresponds to an instance of the Runtime class instantiated by the JVM Runtime. So you won’t find any definition of a constructor in the Runtime class in the JDK documentation. This is because the constructor of the Runtime class itself is private (singleton design). If you want to get a Runtime instance, there are only the following methods:

Runtime run= runtime.getruntime ();

This means that a static getRuntime () method is provided in the Runtime class, which can obtain an instance of the Runtime class and then obtain some system information through the Runtime. For example, getRuntime () gets the Runtime instance; FreeMemory () returns the amount of freeMemory in the Java virtual machine; MaxMemory () returns the maximum amount of memory for the JVM; Gc () runs the garbage collector to free up space; Exec (command) Executes the local command.

package aaa;

import java.io.IOException;

public class RuntimeDemo { public static void main(String[] args) throws IOException,

InterruptedException { // TODO Auto-generated method stub Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec("notepad.exe"); Thread.sleep(5000); p.destroy(); // Destroy runtime.gc(); Exec ("notepad.exe c:\\ runtimedemo.java "); // Open RuntimeDemo with notepad.exe}Copy the code

}

package aaa;

import java.util.Random;

public class MathDemo { public static void main(String[] args) { // TODO Auto-generated method stub

/* * Math: provides methods for manipulating Math operations. It's all static. * Ceil (): Returns the smallest integer greater than the argument. * floor(): Returns the largest integer less than the argument. * round(): Returns a rounded integer. * POw (a,b): A to the power B. */ double d1 = math.ceil (12.56); Double d2 = Math. Floor (12.56); Double d3 = Math. Round (12.46); sop("d1="+d1); sop("d2="+d2); sop("d3="+d3); double d = Math.pow(10, 2); sop("d="+d); For (int I = 0; i < 10; i++) { double d4=(int)(Math.random()*10+1); System.out.println(d4); } // a Random number from 1 to 10 Random =new Random(); for (int i = 0; i < 10; i++) { double d5=(int)(random.nextDouble()*10+1); System.out.println(d5); int d6=random.nextInt(10)+1; System.out.println(d6); } } public static void sop(String string) { System.out.println(string); }Copy the code

}

package aaa;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateDemo { public static void main(String[] args) throws ParseException { // TODO Auto-generated method stub

demo_1(); demo_2(); demo_3(); } /** * puts a string in the date format --> date object. * Use the parse() method of the DateFormat class. * @throws ParseException */ private static void demo_3() throws ParseException { // TODO Auto-generated method stub String str_Date = "April 12, 2015 "; DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG); Date date = dateFormat.parse(str_Date); System.out.println(date); // Convert custom format to date object str_Date="2015-- 08--12"; dateFormat=new SimpleDateFormat("yyyy---MM--dd"); date=dateFormat.parse(str_Date); System.out.println(date); } /** * formats the date object. Puts the date object --> string in the date format. The format method in the DateFormat class is used. */ private static void demo_2() { // TODO Auto-generated method stub Date date = new Date(); DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG); // Format the date system.out.println (dateformat.format (date)); dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); // Format the date and time system.out.println (dateformat.format (date)); DateFormat = new SimpleDateFormat(" YYYY --MM--dd"); String stringDate = dateFormat.format(date); System.out.println(stringDate); } /** * conversion between date object and millisecond value. * * millisecond value --> Date object: 1, through the Date object constructor new Date(timeMillis); 2, can also be set by setTime. * Because you can manipulate the fields (year, month, day, etc.) in the Date object. Date object --> milliseconds value: 2, getTime method. * Because it is possible to calculate with concrete numbers. */ private static void demo_1() { Date date = new Date(); // Encapsulates the current Date and time as a Date object. System.out.println(date); // Sun Apr 29 11:48:02 CST 2012 long time = System.currentTimeMillis(); Date date1 = new Date(time); System.out.println(date1); }Copy the code

}

Exercise: How many days are there between March 17, 2012-4-6?

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

/ *

  • The two dates are subtracted from each other.

  • How to reduce? You have to have two numbers that you can subtract.

  • The energy can be subtracted in milliseconds. How do I get the millisecond value? Through the date object.

  • How do I get a Date object? You can turn a string into a date object.

  • 1. Convert a date-formatted string into a Date object. 2. Convert the Date object to a millisecond value. 3, subtract, become days

* /

public class DateTest { public static void main(String[] args) throws ParseException { String str_date1 = “2012-3-17”;

String str_date2 = "2012-4-18"; test(str_date1,str_date2); } public static void test(String str_date1,String str_date2) throws ParseException { DateFormat dateFormat = DateFormat.getDateInstance(); // Define the date format object. dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = dateFormat.parse(str_date1); //1, convert the date string into a date object. Date date2 = dateFormat.parse(str_date2); long time1 = date1.getTime(); long time2 = date2.getTime(); long time = Math.abs(time1-time2); int day = getDay(time); System.out.println(day); } private static int getDay(long time) { int day = (int)(time/1000/60/60/24); return day; }Copy the code

}

As of JDK1.1, the implementation of the Calendar class is recommended when dealing with dates and times. In terms of design, the function of Calendar class is much more powerful than that of Date class, and it is also more complicated than that of Date class in terms of implementation. Here is an introduction to the use of Calendar class.

The Calendar class is an abstract class that implements specific subclass objects when actually used, and the process of creating the objects is transparent to the programmer, just using the getInstance method.

1. Use the Calendar class to represent the current time

               Calendar c = Calendar.getInstance();
Copy the code

Because the Calendar class is abstract and the constructor of the Calendar class is protected, you cannot use the constructor of the Calendar class to create objects. The getInstance method is provided in the API to create objects.

The Calendar object obtained by using this method represents the current system time. Since the implementation of Calendar class toString is not as intuitive as Date class, it is not meaningful to directly output Calendar class objects.

2. Use the Calendar class to represent the specified time

               Calendar c1 = Calendar.getInstance();

               c1.set(2009, 3 - 1, 9);
Copy the code

To use a Calendar class to represent a specific time, you need to first create a Calendar object and then set the year, month and day parameters in that object to accomplish this.

The set method is declared as:

     public final void set(int year,int month,int date)
Copy the code

The above example code sets the Date to March 9, 2009, and its arguments are not structured the same as the Date class. The value of the year in the Calendar class is written directly. The value of the month is the actual month minus 1, and the value of the date is the actual date.

If you set only a field, such as the value of a date, you can use the set method as follows:

     public void set(int field,int value)
Copy the code

In this method, the parameter field represents the type of field to be set. Common types are as follows:

Calendar.YEAR -- YEAR Calendar.MONTH -- MONTH Calendar.DATE -- DATE Calendar. HOUR_OF_DAY -- 24 hours calendar. MINUTE -- MINUTE calendar. SECOND -- SECOND What day Calendar. DAY_OF_WEEK -- --Copy the code

The subsequent argument value represents the value set to. Such as:

     c1.set(Calendar.DATE,10);
Copy the code

This code sets the date of the c1 object to 10, and all other values are recalculated, such as the day of the week and the corresponding relative time values.

Get the information in the Calendar class

Calendar c2 = Calendar.getInstance(); int year = c2.get(Calendar.YEAR); // year int month = c2.get(calendar. month) + 1; // month int date = c2.get(calendar.date); // date int hour = c2.get(calendar.hour_of_day); // hour int minute = c2.get(calendar.minute); // min int second = c2.get(calendar.second); // secs int day = c2.get(calendar. DAY_OF_WEEK); System.out.println(" year: "+ year); System.out.println(" month: "+ month); System.out.println(" date: "+ date); System.out.println(" hour: "+ hour); System.out.println(" minute: "+ minute); System.out.println(" second: "+ second); System.out.println(" week: "+ day);Copy the code

Public int get(int field) Public int get(int field)

The field parameter represents the value of the field to be obtained, and the field description is the same as the set method above. It is important to note that the month obtained is the actual month value minus 1, the value of week obtained is not the same as the Date class. In the Calendar class, Sunday is 1, Monday is 2, Tuesday is 3, and so on.

4. Explanation of other methods

In fact, the Calendar class provides many other useful methods. Here are a few common methods to use.

Public abstract void add(int field,int amount)

This method adds or subtracts an amount from a field in the Calendar object, making the amount value positive when increasing and the amount value negative when decreasing.

Calendar c3 = calendar.getInstance (); Calendar c3 = calendar.getInstance (); c3.add(Calendar.DATE, 100); int year1 = c3.get(Calendar.YEAR); int month1 = c3.get(Calendar.MONTH) + 1; // month int date1 = c3.get(calendar.date); // date system.out. println(year1 + "year1" + "month1" + date1 + "date "); // Date system.out. println(year1 +" year1 "+" month1 "+ date1 +" date ");Copy the code

The add method adds 100 to the calendar. DATE (or DATE) field of the C3 object, and the class internally recalculates the values of the other fields in the DATE object to get the DATE 100 days later. For example, the program might output June 17, 2009

B, after method: public Boolean after(Object when)

This method determines whether the current date is after when and returns true if it is after when and false otherwise. Such as:

               Calendar c4 = Calendar.getInstance();

               c4.set(2009, 10 - 1, 10);

               Calendar c5 = Calendar.getInstance();

               c5.set(2010, 10 - 1, 10);

               boolean b = c5.after(c4);

               System.out.println(b);
Copy the code

In this sample code, the object C4 represents October 10, 2009, and the object C5 represents October 10, 2010, so the object C5 represents a date after the date c4 represents, so the after method returns true. A similar method is before, which determines whether the current date object precedes another date object.

C, getTime: public final Date getTime()Copy the code

The purpose of this method is to convert a Calendar object to the corresponding Date object, which represents the same point in time.

A similar method is setTime, which converts the Date object into the corresponding Calendar object. The declaration of this method is as follows: public final void setTime(Date Date)

Example code for the conversion is as follows:

Date d = new Date(); Calendar c6 = Calendar.getInstance(); Date d1 = c6.getTime(); Calendar c7 = calendar.getInstance (); c7.setTime(d); Calendar c8 = calendar.getInstance (); Calendar c8 = calendar.getInstance (); long t = 1252785271098L; long t1 = c8.getTimeInMillis(); Calendar c9 = calendar.getInstance (); Calendar c9 = calendar.getInstance (); c9.setTimeInMillis(t1); // Convert relative times to Calendar objectsCopy the code

At conversion time, you can convert a Calendar object to a relative time using the getTimeInMillis method in the Calendar class. When converting the relative time to a Calendar object, you create a Calendar object first and then set the time using the setTimeInMillis method of the Calendar class.

The sample application

Here are two simple examples of the basic use of time and date processing. 1. Calculate the number of days between two datesCopy the code

For example, to calculate the number of days between April 1, 2010 and March 11, 2009, you can use time and date processing.

The program implementation principle is: first of all, on behalf of two specific point in time, using Calendar objects to represent here, and then converted to the corresponding relative time two time points, the relative time difference for two time points, and then the number of milliseconds divided by 1 day (24 hours X60 minutes X60 X1000 milliseconds) can obtain corresponding to the number of days. The complete code to implement the example is as follows:

     import java.util.*;
Copy the code

/ * *

  • Calculate the number of days between two dates

* /

public class DateExample1 {

Public static void main(String[] args) {Calendar c1 = calendar.getInstance (); c1.set(2009, 3 - 1, 11); Calendar c2 = calendar.getInstance (); c2.set(2010, 4 - 1, 1); Long t1 = c1.getTimeInmillis (); long t1 = c1.getTimeInmillis (); long t2 = c2.getTimeInMillis(); long days = (t2 - t1)/(24 * 60 * 60 * 1000); System.out.println(days); }Copy the code

}

2. Output the current month's calendarCopy the code

For example, if the current system time is March 10, 2009, the current system time is March 10, 2009, the current system time is March 10, 2009.

The principle of the program is: first get the day of the week of the 1st of the month, and then get the days of the month, and finally use the process control to output according to the format of the calendar. If the 1st is a Monday, print one space, if the 1st is a Tuesday, print two Spaces, and so on. After printing the date of Saturday, wrap the line. The complete code to implement the example is as follows:

public class DateExample2{

Public static void main(String[] args){Calendar c = Calendar. c.set(Calendar.DATE,1); Int start = c.set (calendar.day_of_week); Int maxDay = c.getActualMaximum(calendar.date); System.out.println(" Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday "); For (int I = 1; i < start; i++){ System.out.print(" "); } for(int I = 1; i <= maxDay; i++){ System.out.print(" " + i); System.out.print(" "); If (I < 10){system.out.print (' '); If ((start + I - 1) % 7 == 0){system.out.println (); } } System.out.println(); / / a newline}Copy the code

}

package cn.itcast.p1.otherapi;

import java.util.Calendar;

public class CalendarDemo {

     public static void main(String[] args) {

              Calendar c = Calendar.getInstance();

              int year = 2012;

              showDays(year);

     }
Copy the code

// How many days are there in February? How many days are there in February

     public static void showDays(int year) {

              Calendar c = Calendar.getInstance();

              c.set(year, 2, 1);

              c.add(Calendar.DAY_OF_MONTH, -1);

              showDate(c);

     }
Copy the code

// Gets the time attribute of the Calendar object

public static void showDate(Calendar c) { int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH)+1; int day = c.get(Calendar.DAY_OF_MONTH); int week = c.get(Calendar.DAY_OF_WEEK); System. The out. Println (" year "+ year + month + + day +", "+" month "getWeek (week)); } public static String getWeek (int I) {String [] weekes = {" ", "Sunday", "Monday" and "Tuesday", "on Wednesday", "Thursday", "Friday", "Saturday"}; return weeks[i]; }Copy the code

}