//原始的Comparable接口
public interface Comparable
{
int compareTo( Object other );
}
//若 Class Employee implements Comparable, 则:
public int compareTo( Object otherObject )
{
Employee other = (Employee) otherObject;
return Double.compare( salary, other.salary );
}
//泛型Comparable接口
public interface Comparable
{
int compareTo( T other );
}
//若 Class Employee implements Comparable
public int compareTo( Employee other )
{
return Double.compare(salary, other.salary);
}
package coreJava_chap6;
import java.util.*;
public class ComparableTest {
public static void main( String[] args ) {
Employee[] staff = new Employee[3];
staff[0] = new Employee( "Cena", 5000, 2015, 3, 12 );
staff[1] = new Employee( "Randy", 3000, 2014, 6, 2 );
staff[2] = new Employee( "Edge", 4000, 2016, 7, 9 );
System.out.println("Original:");
for( Employee e : staff )
System.out.println( "name: " + e.getName() + ", salary: " + e.getSalary() );
Arrays.sort(staff);
System.out.println();
System.out.println("Sorted:");
for( Employee e : staff )
System.out.println( "name: " + e.getName() + ", salary: " + e.getSalary() );
}
}
package coreJava_chap6;
import java.time.*;
public class Employee implements Comparable {
private String name;
private double salary;
private LocalDate hireDay;
public Employee( String name, double salary, int year, int month, int day ) {
this.name = name;
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public LocalDate getHireDay() {
return hireDay;
}
public void raiseSalary( double byPercent ) {
double raise = salary * byPercent / 100;
salary += raise;
}
public int compareTo( Employee other ) {
return Double.compare(salary, other.salary);
}
}
public interface Comparable
{
default int compareTo( T other ) { return 0; }
}
public interface ActionListener
{
void actionPerformed( ActionEvent event );
}
package timer;
import javax.swing.JOptionPane;
import java.util.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
public class TimerTest {
public static void main( String[] args ) {
Timer t = new Timer( 5000, new TimePrinter() );
t.start();
JOptionPane.showMessageDialog(null, "Quit Program?");
System.exit(0);
}
}
class TimePrinter implements ActionListener{
public void actionPerformed( ActionEvent event ) {
System.out.println("Now the time is " + new Date() );
Toolkit.getDefaultToolkit().beep();
}
}
public interface Comparator
{
int compare( T first, T second );
}
package comparator;
import java.util.*;
public class ComparatorTest {
public static void main( String[] args ) {
String[] names = { "Thor", "Tony Stark", "Peter Parker", "Steve" };
System.out.println("Sorted by dictionary order:");
Arrays.sort(names);
for( String s : names ) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("Sorted by string length:");
Arrays.sort(names, new LengthComparator() );
for( String s : names ) {
System.out.print(s + " ");
}
System.out.println();
}
}
class LengthComparator implements Comparator
{
public int compare( String str1, String str2 ) {
return str1.length() - str2.length();
}
}
package clone;
public class CloneTest {
public static void main( String[] args ) {
try {
Employee original = new Employee( "Bryant", 50000 );
original.setHireDay(2012, 3, 12);
Employee cloned = original.clone();
cloned.setHireDay(2005, 2, 23);
System.out.println(original);
System.out.println(cloned);
}catch( Exception e ) {
e.printStackTrace();
}
}
}
package clone;
import java.util.Date;
import java.util.GregorianCalendar;
public class Employee implements Cloneable {
private String name;
private double salary;
private Date hireDay;
public Employee( String name, double salary ) {
this.name = name;
this.salary = salary;
this.hireDay = new Date();
}
public Employee clone() throws CloneNotSupportedException{
Employee cloned = ( Employee) super.clone();
cloned.hireDay = (Date) hireDay.clone();
return cloned;
}
public void setHireDay( int year, int month, int day ) {
Date newHireDay = new GregorianCalendar(year, month - 1, day ).getTime();
hireDay.setTime(newHireDay.getTime());
}
public void raiseSalary( double byPercent ) {
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString() {
return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
}
}
package lambda;
import java.util.Arrays;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class LambdaTest {
public static void main( String[] args ) {
String[] strs = { "Hulk", "James", "Leo", "Bryant" };
System.out.println("Sorted by dictionary order:");
Arrays.sort(strs);
System.out.println( Arrays.toString(strs) );
System.out.println("Sorted by string length:");
Arrays.sort(strs, (String first, String second) -> first.length() - second.length() );
System.out.println( Arrays.toString(strs) );
Timer t = new Timer( 3000, event -> System.out.println( "Now the time is " + new Date() ) );
t.start();
JOptionPane.showMessageDialog(null, "Quit now?");
System.exit(0);
}
}
public interface Predicate
{
boolean test(T t);
//...addition default and static methods
}
package funcInterface;
import java.util.function.*;
public class FuncInterfaceTest {
public static void main( String[] args ) {
repeat( 10, ()->System.out.println("Life is a struggle!") );
countDown( 10, i -> System.out.println("count down to " + (10-i)) );
int[] intArr = { 4, 2, 5, 9, 6, 7, 1, 3 };
boringTest( intArr, x -> x >= 5 );
}
public static void repeat( int n, Runnable action ) {
for( int i = 0; i < n; i++ ) {
action.run();
}
}
public static void countDown( int n, IntConsumer action ) {
for( int i = 0; i < n; i++ ) action.accept(i);
}
public static void boringTest( int[] a, IntPredicate action ) {
for( int e : a ) {
if( action.test(e) ) System.out.println( "Element " + e + " satisfies the test." );
else System.out.println( "Element " + e + " dissatisfies the test." );
}
}
}
package comparator;
import java.util.Arrays;
import java.util.Comparator;
public class ComparatorTest2 {
public static void main( String[] args ) {
Person[] people = new Person[3];
people[0] = new Person( "Albus", null, "DumbleDore" );
people[1] = new Person( "Tom", "Marvolo", "Riddle" );
people[2] = new Person( "Albus", "Severus", "Potter" );
Arrays.sort(people, Comparator.comparing(Person::getName));
for( Person p : people ) {
System.out.print(p.getName() + " ");
}
System.out.println();
Arrays.sort(people, Comparator.comparing( Person::getName,
(first,second) -> first.length() - second.length() ) );
for( Person p : people ) {
System.out.print(p.getName() + " ");
}
System.out.println();
Arrays.sort(people,Comparator.comparing(Person::getMiddleName,
Comparator.nullsFirst(Comparator.naturalOrder() )));
for( Person p : people ) {
System.out.print(p.getName() + " ");
}
System.out.println();
}
}
package innerClass;
import javax.swing.*;
public class InnerClassTest {
public static void main( String[] args ) {
TalkingClock clock = new TalkingClock(5000, true);
clock.start();
JOptionPane.showMessageDialog(null, "Quit now?");
System.exit(0);
}
}
package innerClass;
import javax.swing.*;
public class InnerClassTest {
public static void main( String[] args ) {
TalkingClock clock = new TalkingClock(5000, true);
clock.start();
JOptionPane.showMessageDialog(null, "Quit now?");
System.exit(0);
}
}
public void start( int interval, boolean beep )
{
ActionListener listener = new ActionLister()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("Now the time is " + new Date() );
if( beep ) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer( 1000, listener );
t.start();
}
//通用语法格式1:
new SuperType( construction parameters )
{
inner class methods and data
}
//通用语法格式2:
new Interface()
{
methods and data
}
package anonymousInnerClass;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.Timer;
public class AnonymousInnerClassTest {
public static void main( String[] args ) {
TalkingClock clock = new TalkingClock();
clock.start(1000, true);
JOptionPane.showMessageDialog(null, "Quit now?");
System.exit(0);
}
}
class TalkingClock{
public void start( int interval, boolean beep ) {
ActionListener listener = new ActionListener() {
public void actionPerformed( ActionEvent event ) {
System.out.println("Now the time is " + new Date());
if( beep ) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(interval,listener);
t.start();
}
}
ArrayList friends = new ArrayList();
friends.add("Harry");
friends.add("Tony");
invite(friends);
//等价于:
invite( new ArrayList(){ { add("Harry"); add("Tony"); } } );
//外层括号建立了 ArrayList 的一个 匿名子类。内层括号则是一个 对象构造块。
package staticInnerClass;
import java.util.*;
public class StaticInnerClassTest {
public static void main( String[] args ) {
int[] arr = new int[10];
for( int i = 0; i < 10; i++ )
arr[i] = (int) ( 100 * Math.random() );
System.out.println(Arrays.toString(arr));
ArrayAlg.Pair ans = ArrayAlg.minmax(arr);
System.out.println("min=" + ans.getFirst());
System.out.println("max=" + ans.getSecond());
}
}
class ArrayAlg{
public static class Pair{
private int first;
private int second;
public Pair( int first, int second ) {
this.first = first;
this.second = second;
}
public int getFirst() { return first; }
public int getSecond() { return second; }
}
public static Pair minmax( int[] intArr ) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for( int d : intArr ) {
if( d > max ) max = d;
if( d < min ) min = d;
}
return new Pair(min,max);
}
}
package proxy;
import java.lang.reflect.*;
import java.util.*;
public class ProxyTest {
public static void main( String[] args ) {
Object[] elements = new Object[1000];
for( int i = 0; i < elements.length; i++ ) {
Integer value = i + 1;
InvocationHandler handler = new TraceHandler(value);
Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class }, handler );
elements[i] = proxy;
}
Integer key = new Random().nextInt(elements.length) + 1;
int result = Arrays.binarySearch(elements, key);
if( result >= 0 ) System.out.println( elements[result] );
}
}
class TraceHandler implements InvocationHandler{
private Object target;
public TraceHandler( Object obj ) {
target = obj;
}
public Object invoke( Object proxy, Method m, Object[] args ) throws Throwable{
System.out.print(target);
System.out.print("." + m.getName() + "(");
if( args != null ) {
for( int i = 0; i < args.length; i++ ) {
System.out.print(args[i]);
if( i < args.length - 1 ) System.out.print(", ");
}
}
System.out.println(")");
return m.invoke(target, args);
}
}