rm corejava第11版
@@ -1,67 +0,0 @@
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
|
||||
import javafx.application.*;
|
||||
import javafx.scene.*;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.control.Alert.*;
|
||||
import javafx.scene.image.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.*;
|
||||
import javafx.stage.FileChooser.*;
|
||||
|
||||
/**
|
||||
* A program for viewing images.
|
||||
* @version 1.40 2017-12-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ImageViewer extends Application
|
||||
{
|
||||
private static final int MIN_SIZE = 400;
|
||||
|
||||
public void start(Stage stage) throws IOException
|
||||
{
|
||||
BorderPane pane = new BorderPane();
|
||||
MenuBar bar = new MenuBar();
|
||||
pane.setTop(bar);
|
||||
Menu fileMenu = new Menu("File");
|
||||
bar.getMenus().add(fileMenu);
|
||||
MenuItem openItem = new MenuItem("Open");
|
||||
openItem.setOnAction(event -> load(stage, pane));
|
||||
MenuItem exitItem = new MenuItem("Exit");
|
||||
exitItem.setOnAction(event -> System.exit(0));
|
||||
fileMenu.getItems().addAll(openItem, exitItem);
|
||||
stage.setScene(new Scene(pane, MIN_SIZE, MIN_SIZE));
|
||||
stage.setTitle("ImageViewer");
|
||||
stage.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads an image.
|
||||
* @param stage the stage above which to place the file chooser
|
||||
* @param pane the pane into which to place the image view
|
||||
*/
|
||||
public void load(Stage stage, BorderPane pane)
|
||||
{
|
||||
FileChooser fileChooser = new FileChooser();
|
||||
fileChooser.getExtensionFilters().addAll(
|
||||
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
|
||||
new ExtensionFilter("All Files", "*.*"));
|
||||
File file = fileChooser.showOpenDialog(stage);
|
||||
if (file != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
Path path = file.toPath();
|
||||
Image image = new Image(Files.newInputStream(path));
|
||||
pane.setCenter(new ImageView(image));
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
Alert alert = new Alert(AlertType.ERROR,
|
||||
"Cannot open file.");
|
||||
alert.showAndWait();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
@@ -1,68 +0,0 @@
|
||||
import java.awt.*;
|
||||
import java.io.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A program for viewing images.
|
||||
* @version 1.31 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ImageViewer
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() -> {
|
||||
var frame = new ImageViewerFrame();
|
||||
frame.setTitle("ImageViewer");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a label to show an image.
|
||||
*/
|
||||
class ImageViewerFrame extends JFrame
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
public ImageViewerFrame()
|
||||
{
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// use a label to display the images
|
||||
var label = new JLabel();
|
||||
add(label);
|
||||
|
||||
// set up the file chooser
|
||||
var chooser = new JFileChooser();
|
||||
chooser.setCurrentDirectory(new File("."));
|
||||
|
||||
// set up the menu bar
|
||||
var menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
|
||||
var menu = new JMenu("File");
|
||||
menuBar.add(menu);
|
||||
|
||||
var openItem = new JMenuItem("Open");
|
||||
menu.add(openItem);
|
||||
openItem.addActionListener(event -> {
|
||||
// show file chooser dialog
|
||||
int result = chooser.showOpenDialog(null);
|
||||
|
||||
// if file selected, set it as icon of the label
|
||||
if (result == JFileChooser.APPROVE_OPTION)
|
||||
{
|
||||
String name = chooser.getSelectedFile().getPath();
|
||||
label.setIcon(new ImageIcon(name));
|
||||
}
|
||||
});
|
||||
|
||||
var exitItem = new JMenuItem("Exit");
|
||||
menu.add(exitItem);
|
||||
exitItem.addActionListener(event -> System.exit(0));
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
@@ -1,16 +0,0 @@
|
||||
/**
|
||||
* This program displays a greeting for the reader.
|
||||
* @version 1.30 2014-02-27
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Welcome
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
String greeting = "Welcome to Core Java!";
|
||||
System.out.println(greeting);
|
||||
for (int i = 0; i < greeting.length(); i++)
|
||||
System.out.print("=");
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import java.math.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program uses big numbers to compute the odds of winning the grand prize in a lottery.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class BigIntegerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How many numbers do you need to draw? ");
|
||||
int k = in.nextInt();
|
||||
|
||||
System.out.print("What is the highest number you can draw? ");
|
||||
int n = in.nextInt();
|
||||
|
||||
/*
|
||||
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
|
||||
*/
|
||||
|
||||
BigInteger lotteryOdds = BigInteger.valueOf(1);
|
||||
|
||||
for (int i = 1; i <= k; i++)
|
||||
lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide(
|
||||
BigInteger.valueOf(i));
|
||||
|
||||
System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* This program shows how to store tabular data in a 2D array.
|
||||
* @version 1.40 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CompoundInterest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
final double STARTRATE = 10;
|
||||
final int NRATES = 6;
|
||||
final int NYEARS = 10;
|
||||
|
||||
// set interest rates to 10 . . . 15%
|
||||
double[] interestRate = new double[NRATES];
|
||||
for (int j = 0; j < interestRate.length; j++)
|
||||
interestRate[j] = (STARTRATE + j) / 100.0;
|
||||
|
||||
double[][] balances = new double[NYEARS][NRATES];
|
||||
|
||||
// set initial balances to 10000
|
||||
for (int j = 0; j < balances[0].length; j++)
|
||||
balances[0][j] = 10000;
|
||||
|
||||
// compute interest for future years
|
||||
for (int i = 1; i < balances.length; i++)
|
||||
{
|
||||
for (int j = 0; j < balances[i].length; j++)
|
||||
{
|
||||
// get last year's balances from previous row
|
||||
double oldBalance = balances[i - 1][j];
|
||||
|
||||
// compute interest
|
||||
double interest = oldBalance * interestRate[j];
|
||||
|
||||
// compute this year's balances
|
||||
balances[i][j] = oldBalance + interest;
|
||||
}
|
||||
}
|
||||
|
||||
// print one row of interest rates
|
||||
for (int j = 0; j < interestRate.length; j++)
|
||||
System.out.printf("%9.0f%%", 100 * interestRate[j]);
|
||||
|
||||
System.out.println();
|
||||
|
||||
// print balance table
|
||||
for (double[] row : balances)
|
||||
{
|
||||
// print table row
|
||||
for (double b : row)
|
||||
System.out.printf("%10.2f", b);
|
||||
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
/**
|
||||
* This is the first sample program in Core Java Chapter 3
|
||||
* @version 1.01 1997-03-22
|
||||
* @author Gary Cornell
|
||||
*/
|
||||
public class FirstSample
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
System.out.println("We will not use 'Hello, World!'");
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates console input.
|
||||
* @version 1.10 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class InputTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
// get first input
|
||||
System.out.print("What is your name? ");
|
||||
String name = in.nextLine();
|
||||
|
||||
// get second input
|
||||
System.out.print("How old are you? ");
|
||||
int age = in.nextInt();
|
||||
|
||||
// display output on console
|
||||
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/**
|
||||
* This program demonstrates a triangular array.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LotteryArray
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
final int NMAX = 10;
|
||||
|
||||
// allocate triangular array
|
||||
int[][] odds = new int[NMAX + 1][];
|
||||
for (int n = 0; n <= NMAX; n++)
|
||||
odds[n] = new int[n + 1];
|
||||
|
||||
// fill triangular array
|
||||
for (int n = 0; n < odds.length; n++)
|
||||
for (int k = 0; k < odds[n].length; k++)
|
||||
{
|
||||
/*
|
||||
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
|
||||
*/
|
||||
int lotteryOdds = 1;
|
||||
for (int i = 1; i <= k; i++)
|
||||
lotteryOdds = lotteryOdds * (n - i + 1) / i;
|
||||
|
||||
odds[n][k] = lotteryOdds;
|
||||
}
|
||||
|
||||
// print triangular array
|
||||
for (int[] row : odds)
|
||||
{
|
||||
for (int odd : row)
|
||||
System.out.printf("%4d", odd);
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates array manipulation.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LotteryDrawing
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How many numbers do you need to draw? ");
|
||||
int k = in.nextInt();
|
||||
|
||||
System.out.print("What is the highest number you can draw? ");
|
||||
int n = in.nextInt();
|
||||
|
||||
// fill an array with numbers 1 2 3 . . . n
|
||||
int[] numbers = new int[n];
|
||||
for (int i = 0; i < numbers.length; i++)
|
||||
numbers[i] = i + 1;
|
||||
|
||||
// draw k numbers and put them into a second array
|
||||
int[] result = new int[k];
|
||||
for (int i = 0; i < result.length; i++)
|
||||
{
|
||||
// make a random index between 0 and n - 1
|
||||
int r = (int) (Math.random() * n);
|
||||
|
||||
// pick the element at the random location
|
||||
result[i] = numbers[r];
|
||||
|
||||
// move the last element into the random location
|
||||
numbers[r] = numbers[n - 1];
|
||||
n--;
|
||||
}
|
||||
|
||||
// print the sorted array
|
||||
Arrays.sort(result);
|
||||
System.out.println("Bet the following combination. It'll make you rich!");
|
||||
for (int r : result)
|
||||
System.out.println(r);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates a <code>for</code> loop.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LotteryOdds
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How many numbers do you need to draw? ");
|
||||
int k = in.nextInt();
|
||||
|
||||
System.out.print("What is the highest number you can draw? ");
|
||||
int n = in.nextInt();
|
||||
|
||||
/*
|
||||
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
|
||||
*/
|
||||
|
||||
int lotteryOdds = 1;
|
||||
for (int i = 1; i <= k; i++)
|
||||
lotteryOdds = lotteryOdds * (n - i + 1) / i;
|
||||
|
||||
System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates a <code>while</code> loop.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Retirement
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// read inputs
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How much money do you need to retire? ");
|
||||
double goal = in.nextDouble();
|
||||
|
||||
System.out.print("How much money will you contribute every year? ");
|
||||
double payment = in.nextDouble();
|
||||
|
||||
System.out.print("Interest rate in %: ");
|
||||
double interestRate = in.nextDouble();
|
||||
|
||||
double balance = 0;
|
||||
int years = 0;
|
||||
|
||||
// update account balance while goal isn't reached
|
||||
while (balance < goal)
|
||||
{
|
||||
// add this year's payment and interest
|
||||
balance += payment;
|
||||
double interest = balance * interestRate / 100;
|
||||
balance += interest;
|
||||
years++;
|
||||
}
|
||||
|
||||
System.out.println("You can retire in " + years + " years.");
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates a <code>do/while</code> loop.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Retirement2
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How much money will you contribute every year? ");
|
||||
double payment = in.nextDouble();
|
||||
|
||||
System.out.print("Interest rate in %: ");
|
||||
double interestRate = in.nextDouble();
|
||||
|
||||
double balance = 0;
|
||||
int year = 0;
|
||||
|
||||
String input;
|
||||
|
||||
// update account balance while user isn't ready to retire
|
||||
do
|
||||
{
|
||||
// add this year's payment and interest
|
||||
balance += payment;
|
||||
double interest = balance * interestRate / 100;
|
||||
balance += interest;
|
||||
|
||||
year++;
|
||||
|
||||
// print current balance
|
||||
System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
|
||||
|
||||
// ask if ready to retire and get input
|
||||
System.out.print("Ready to retire? (Y/N) ");
|
||||
input = in.next();
|
||||
}
|
||||
while (input.equals("N"));
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* @version 1.5 2015-05-08
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CalendarTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
LocalDate date = LocalDate.now();
|
||||
int month = date.getMonthValue();
|
||||
int today = date.getDayOfMonth();
|
||||
|
||||
date = date.minusDays(today - 1); // set to start of month
|
||||
DayOfWeek weekday = date.getDayOfWeek();
|
||||
int value = weekday.getValue(); // 1 = Monday, . . . , 7 = Sunday
|
||||
|
||||
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
|
||||
for (int i = 1; i < value; i++)
|
||||
System.out.print(" ");
|
||||
while (date.getMonthValue() == month)
|
||||
{
|
||||
System.out.printf("%3d", date.getDayOfMonth());
|
||||
if (date.getDayOfMonth() == today)
|
||||
System.out.print("*");
|
||||
else
|
||||
System.out.print(" ");
|
||||
date = date.plusDays(1);
|
||||
if (date.getDayOfWeek().getValue() == 1) System.out.println();
|
||||
}
|
||||
if (date.getDayOfWeek().getValue() != 1) System.out.println();
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates object construction.
|
||||
* @version 1.02 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ConstructorTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array with three Employee objects
|
||||
var staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Harry", 40000);
|
||||
staff[1] = new Employee(60000);
|
||||
staff[2] = new Employee();
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary="
|
||||
+ e.getSalary());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
private static int nextId;
|
||||
|
||||
private int id;
|
||||
private String name = ""; // instance field initialization
|
||||
private double salary;
|
||||
|
||||
// static initialization block
|
||||
static
|
||||
{
|
||||
var generator = new Random();
|
||||
// set nextId to a random number between 0 and 9999
|
||||
nextId = generator.nextInt(10000);
|
||||
}
|
||||
|
||||
// object initialization block
|
||||
{
|
||||
id = nextId;
|
||||
nextId++;
|
||||
}
|
||||
|
||||
// three overloaded constructors
|
||||
public Employee(String n, double s)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
}
|
||||
|
||||
public Employee(double s)
|
||||
{
|
||||
// calls the Employee(String, double) constructor
|
||||
this("Employee #" + nextId, s);
|
||||
}
|
||||
|
||||
// the default constructor
|
||||
public Employee()
|
||||
{
|
||||
// name initialized to ""--see above
|
||||
// salary not explicitly set--initialized to 0
|
||||
// id initialized in initialization block
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public int getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* This program tests the Employee class.
|
||||
* @version 1.13 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EmployeeTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array with three Employee objects
|
||||
Employee[] staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
|
||||
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
|
||||
|
||||
// raise everyone's salary by 5%
|
||||
for (Employee e : staff)
|
||||
e.raiseSalary(5);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
|
||||
+ e.getHireDay());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
private LocalDate hireDay;
|
||||
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import com.horstmann.corejava.*;
|
||||
// the Employee class is defined in that package
|
||||
|
||||
import static java.lang.System.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of packages.
|
||||
* @version 1.11 2004-02-19
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PackageTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// because of the import statement, we don't have to use
|
||||
// com.horstmann.corejava.Employee here
|
||||
var harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
|
||||
harry.raiseSalary(5);
|
||||
|
||||
// because of the static import statement, we don't have to use System.out here
|
||||
out.println("name=" + harry.getName() + ",salary=" + harry.getSalary());
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.horstmann.corejava;
|
||||
|
||||
// the classes in this file are part of this package
|
||||
|
||||
import java.time.*;
|
||||
|
||||
// import statements come after the package statement
|
||||
|
||||
/**
|
||||
* @version 1.11 2015-05-08
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Employee
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
/**
|
||||
* This program demonstrates parameter passing in Java.
|
||||
* @version 1.01 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ParamTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
/*
|
||||
* Test 1: Methods can't modify numeric parameters
|
||||
*/
|
||||
System.out.println("Testing tripleValue:");
|
||||
double percent = 10;
|
||||
System.out.println("Before: percent=" + percent);
|
||||
tripleValue(percent);
|
||||
System.out.println("After: percent=" + percent);
|
||||
|
||||
/*
|
||||
* Test 2: Methods can change the state of object parameters
|
||||
*/
|
||||
System.out.println("\nTesting tripleSalary:");
|
||||
var harry = new Employee("Harry", 50000);
|
||||
System.out.println("Before: salary=" + harry.getSalary());
|
||||
tripleSalary(harry);
|
||||
System.out.println("After: salary=" + harry.getSalary());
|
||||
|
||||
/*
|
||||
* Test 3: Methods can't attach new objects to object parameters
|
||||
*/
|
||||
System.out.println("\nTesting swap:");
|
||||
var a = new Employee("Alice", 70000);
|
||||
var b = new Employee("Bob", 60000);
|
||||
System.out.println("Before: a=" + a.getName());
|
||||
System.out.println("Before: b=" + b.getName());
|
||||
swap(a, b);
|
||||
System.out.println("After: a=" + a.getName());
|
||||
System.out.println("After: b=" + b.getName());
|
||||
}
|
||||
|
||||
public static void tripleValue(double x) // doesn't work
|
||||
{
|
||||
x = 3 * x;
|
||||
System.out.println("End of method: x=" + x);
|
||||
}
|
||||
|
||||
public static void tripleSalary(Employee x) // works
|
||||
{
|
||||
x.raiseSalary(200);
|
||||
System.out.println("End of method: salary=" + x.getSalary());
|
||||
}
|
||||
|
||||
public static void swap(Employee x, Employee y)
|
||||
{
|
||||
Employee temp = x;
|
||||
x = y;
|
||||
y = temp;
|
||||
System.out.println("End of method: x=" + x.getName());
|
||||
System.out.println("End of method: y=" + y.getName());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee // simplified Employee class
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
|
||||
public Employee(String n, double s)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* This program demonstrates static methods.
|
||||
* @version 1.02 2008-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class StaticTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array with three Employee objects
|
||||
var staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Tom", 40000);
|
||||
staff[1] = new Employee("Dick", 60000);
|
||||
staff[2] = new Employee("Harry", 65000);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
{
|
||||
e.setId();
|
||||
System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary="
|
||||
+ e.getSalary());
|
||||
}
|
||||
|
||||
int n = Employee.getNextId(); // calls static method
|
||||
System.out.println("Next available id=" + n);
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
private static int nextId = 1;
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private int id;
|
||||
|
||||
public Employee(String n, double s)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
id = 0;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public int getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId()
|
||||
{
|
||||
id = nextId; // set id to next available id
|
||||
nextId++;
|
||||
}
|
||||
|
||||
public static int getNextId()
|
||||
{
|
||||
return nextId; // returns static field
|
||||
}
|
||||
|
||||
public static void main(String[] args) // unit test
|
||||
{
|
||||
var e = new Employee("Harry", 50000);
|
||||
System.out.println(e.getName() + " " + e.getSalary());
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package abstractClasses;
|
||||
|
||||
import java.time.*;
|
||||
|
||||
public class Employee extends Person
|
||||
{
|
||||
private double salary;
|
||||
private LocalDate hireDay;
|
||||
|
||||
public Employee(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
super(name);
|
||||
this.salary = salary;
|
||||
hireDay = LocalDate.of(year, month, day);
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public LocalDate getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public String getDescription()
|
||||
{
|
||||
return String.format("an employee with a salary of $%.2f", salary);
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package abstractClasses;
|
||||
|
||||
public abstract class Person
|
||||
{
|
||||
public abstract String getDescription();
|
||||
private String name;
|
||||
|
||||
public Person(String name)
|
||||
{
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package abstractClasses;
|
||||
|
||||
/**
|
||||
* This program demonstrates abstract classes.
|
||||
* @version 1.01 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PersonTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var people = new Person[2];
|
||||
|
||||
// fill the people array with Student and Employee objects
|
||||
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
people[1] = new Student("Maria Morris", "computer science");
|
||||
|
||||
// print out names and descriptions of all Person objects
|
||||
for (Person p : people)
|
||||
System.out.println(p.getName() + ", " + p.getDescription());
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package abstractClasses;
|
||||
|
||||
public class Student extends Person
|
||||
{
|
||||
private String major;
|
||||
|
||||
/**
|
||||
* @param name the student's name
|
||||
* @param major the student's major
|
||||
*/
|
||||
public Student(String name, String major)
|
||||
{
|
||||
// pass name to superclass constructor
|
||||
super(name);
|
||||
this.major = major;
|
||||
}
|
||||
|
||||
public String getDescription()
|
||||
{
|
||||
return "a student majoring in " + major;
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package arrayList;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the ArrayList class.
|
||||
* @version 1.11 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ArrayListTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array list with three Employee objects
|
||||
var staff = new ArrayList<Employee>();
|
||||
|
||||
staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
|
||||
staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
|
||||
staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
|
||||
|
||||
// raise everyone's salary by 5%
|
||||
for (Employee e : staff)
|
||||
e.raiseSalary(5);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
|
||||
+ e.getHireDay());
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package arrayList;
|
||||
|
||||
import java.time.*;
|
||||
|
||||
public class Employee
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package arrays;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of reflection for manipulating arrays.
|
||||
* @version 1.2 2012-05-04
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CopyOfTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int[] a = { 1, 2, 3 };
|
||||
a = (int[]) goodCopyOf(a, 10);
|
||||
System.out.println(Arrays.toString(a));
|
||||
|
||||
String[] b = { "Tom", "Dick", "Harry" };
|
||||
b = (String[]) goodCopyOf(b, 10);
|
||||
System.out.println(Arrays.toString(b));
|
||||
|
||||
System.out.println("The following call will generate an exception.");
|
||||
b = (String[]) badCopyOf(b, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method attempts to grow an array by allocating a new array and copying all elements.
|
||||
* @param a the array to grow
|
||||
* @param newLength the new length
|
||||
* @return a larger array that contains all elements of a. However, the returned
|
||||
* array has type Object[], not the same type as a
|
||||
*/
|
||||
public static Object[] badCopyOf(Object[] a, int newLength) // not useful
|
||||
{
|
||||
var newArray = new Object[newLength];
|
||||
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
|
||||
return newArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method grows an array by allocating a new array of the same type and
|
||||
* copying all elements.
|
||||
* @param a the array to grow. This can be an object array or a primitive
|
||||
* type array
|
||||
* @return a larger array that contains all elements of a.
|
||||
*/
|
||||
public static Object goodCopyOf(Object a, int newLength)
|
||||
{
|
||||
Class cl = a.getClass();
|
||||
if (!cl.isArray()) return null;
|
||||
Class componentType = cl.getComponentType();
|
||||
int length = Array.getLength(a);
|
||||
Object newArray = Array.newInstance(componentType, newLength);
|
||||
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
|
||||
return newArray;
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
Core Java
|
||||
@@ -1,33 +0,0 @@
|
||||
package enums;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates enumerated types.
|
||||
* @version 1.0 2004-05-24
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EnumTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var in = new Scanner(System.in);
|
||||
System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
|
||||
String input = in.next().toUpperCase();
|
||||
Size size = Enum.valueOf(Size.class, input);
|
||||
System.out.println("size=" + size);
|
||||
System.out.println("abbreviation=" + size.getAbbreviation());
|
||||
if (size == Size.EXTRA_LARGE)
|
||||
System.out.println("Good job--you paid attention to the _.");
|
||||
}
|
||||
}
|
||||
|
||||
enum Size
|
||||
{
|
||||
SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
|
||||
|
||||
private Size(String abbreviation) { this.abbreviation = abbreviation; }
|
||||
public String getAbbreviation() { return abbreviation; }
|
||||
|
||||
private String abbreviation;
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package equals;
|
||||
|
||||
import java.time.*;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Employee
|
||||
{
|
||||
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 boolean equals(Object otherObject)
|
||||
{
|
||||
// a quick test to see if the objects are identical
|
||||
if (this == otherObject) return true;
|
||||
|
||||
// must return false if the explicit parameter is null
|
||||
if (otherObject == null) return false;
|
||||
|
||||
// if the classes don't match, they can't be equal
|
||||
if (getClass() != otherObject.getClass()) return false;
|
||||
|
||||
// now we know otherObject is a non-null Employee
|
||||
var other = (Employee) otherObject;
|
||||
|
||||
// test whether the fields have identical values
|
||||
return Objects.equals(name, other.name)
|
||||
&& salary == other.salary && Objects.equals(hireDay, other.hireDay);
|
||||
}
|
||||
|
||||
public int hashCode()
|
||||
{
|
||||
return Objects.hash(name, salary, hireDay);
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay="
|
||||
+ hireDay + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package equals;
|
||||
|
||||
/**
|
||||
* This program demonstrates the equals method.
|
||||
* @version 1.12 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EqualsTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
|
||||
var alice2 = alice1;
|
||||
var alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
|
||||
var bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
|
||||
|
||||
System.out.println("alice1 == alice2: " + (alice1 == alice2));
|
||||
|
||||
System.out.println("alice1 == alice3: " + (alice1 == alice3));
|
||||
|
||||
System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
|
||||
|
||||
System.out.println("alice1.equals(bob): " + alice1.equals(bob));
|
||||
|
||||
System.out.println("bob.toString(): " + bob);
|
||||
|
||||
var carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
|
||||
var boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
|
||||
boss.setBonus(5000);
|
||||
System.out.println("boss.toString(): " + boss);
|
||||
System.out.println("carl.equals(boss): " + carl.equals(boss));
|
||||
System.out.println("alice1.hashCode(): " + alice1.hashCode());
|
||||
System.out.println("alice3.hashCode(): " + alice3.hashCode());
|
||||
System.out.println("bob.hashCode(): " + bob.hashCode());
|
||||
System.out.println("carl.hashCode(): " + carl.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package equals;
|
||||
|
||||
public class Manager extends Employee
|
||||
{
|
||||
private double bonus;
|
||||
|
||||
public Manager(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
super(name, salary, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double bonus)
|
||||
{
|
||||
this.bonus = bonus;
|
||||
}
|
||||
|
||||
public boolean equals(Object otherObject)
|
||||
{
|
||||
if (!super.equals(otherObject)) return false;
|
||||
var other = (Manager) otherObject;
|
||||
// super.equals checked that this and other belong to the same class
|
||||
return bonus == other.bonus;
|
||||
}
|
||||
|
||||
public int hashCode()
|
||||
{
|
||||
return java.util.Objects.hash(super.hashCode(), bonus);
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return super.toString() + "[bonus=" + bonus + "]";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
package inheritance;
|
||||
|
||||
import java.time.*;
|
||||
|
||||
public class Employee
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package inheritance;
|
||||
|
||||
public class Manager extends Employee
|
||||
{
|
||||
private double bonus;
|
||||
|
||||
/**
|
||||
* @param name the employee's name
|
||||
* @param salary the salary
|
||||
* @param year the hire year
|
||||
* @param month the hire month
|
||||
* @param day the hire day
|
||||
*/
|
||||
public Manager(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
super(name, salary, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double b)
|
||||
{
|
||||
bonus = b;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package inheritance;
|
||||
|
||||
/**
|
||||
* This program demonstrates inheritance.
|
||||
* @version 1.21 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ManagerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// construct a Manager object
|
||||
var boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
|
||||
boss.setBonus(5000);
|
||||
|
||||
var staff = new Employee[3];
|
||||
|
||||
// fill the staff array with Manager and Employee objects
|
||||
|
||||
staff[0] = boss;
|
||||
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package methods;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
|
||||
/**
|
||||
* This program shows how to invoke methods through reflection.
|
||||
* @version 1.2 2012-05-04
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class MethodTableTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
throws ReflectiveOperationException
|
||||
{
|
||||
// get method pointers to the square and sqrt methods
|
||||
Method square = MethodTableTest.class.getMethod("square", double.class);
|
||||
Method sqrt = Math.class.getMethod("sqrt", double.class);
|
||||
|
||||
// print tables of x- and y-values
|
||||
printTable(1, 10, 10, square);
|
||||
printTable(1, 10, 10, sqrt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the square of a number
|
||||
* @param x a number
|
||||
* @return x squared
|
||||
*/
|
||||
public static double square(double x)
|
||||
{
|
||||
return x * x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a table with x- and y-values for a method
|
||||
* @param from the lower bound for the x-values
|
||||
* @param to the upper bound for the x-values
|
||||
* @param n the number of rows in the table
|
||||
* @param f a method with a double parameter and double return value
|
||||
*/
|
||||
public static void printTable(double from, double to, int n, Method f)
|
||||
throws ReflectiveOperationException
|
||||
{
|
||||
// print out the method as table header
|
||||
System.out.println(f);
|
||||
|
||||
double dx = (to - from) / (n - 1);
|
||||
|
||||
for (double x = from; x <= to; x += dx)
|
||||
{
|
||||
double y = (Double) f.invoke(null, x);
|
||||
System.out.printf("%10.4f | %10.4f%n", x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package objectAnalyzer;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class ObjectAnalyzer
|
||||
{
|
||||
private ArrayList<Object> visited = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Converts an object to a string representation that lists all fields.
|
||||
* @param obj an object
|
||||
* @return a string with the object's class name and all field names and values
|
||||
*/
|
||||
public String toString(Object obj)
|
||||
throws ReflectiveOperationException
|
||||
{
|
||||
if (obj == null) return "null";
|
||||
if (visited.contains(obj)) return "...";
|
||||
visited.add(obj);
|
||||
Class cl = obj.getClass();
|
||||
if (cl == String.class) return (String) obj;
|
||||
if (cl.isArray())
|
||||
{
|
||||
String r = cl.getComponentType() + "[]{";
|
||||
for (int i = 0; i < Array.getLength(obj); i++)
|
||||
{
|
||||
if (i > 0) r += ",";
|
||||
Object val = Array.get(obj, i);
|
||||
if (cl.getComponentType().isPrimitive()) r += val;
|
||||
else r += toString(val);
|
||||
}
|
||||
return r + "}";
|
||||
}
|
||||
|
||||
String r = cl.getName();
|
||||
// inspect the fields of this class and all superclasses
|
||||
do
|
||||
{
|
||||
r += "[";
|
||||
Field[] fields = cl.getDeclaredFields();
|
||||
AccessibleObject.setAccessible(fields, true);
|
||||
// get the names and values of all fields
|
||||
for (Field f : fields)
|
||||
{
|
||||
if (!Modifier.isStatic(f.getModifiers()))
|
||||
{
|
||||
if (!r.endsWith("[")) r += ",";
|
||||
r += f.getName() + "=";
|
||||
Class t = f.getType();
|
||||
Object val = f.get(obj);
|
||||
if (t.isPrimitive()) r += val;
|
||||
else r += toString(val);
|
||||
}
|
||||
}
|
||||
r += "]";
|
||||
cl = cl.getSuperclass();
|
||||
}
|
||||
while (cl != null);
|
||||
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package objectAnalyzer;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program uses reflection to spy on objects.
|
||||
* @version 1.13 2018-03-16
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ObjectAnalyzerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
throws ReflectiveOperationException
|
||||
{
|
||||
var squares = new ArrayList<Integer>();
|
||||
for (int i = 1; i <= 5; i++)
|
||||
squares.add(i * i);
|
||||
System.out.println(new ObjectAnalyzer().toString(squares));
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package reflection;
|
||||
|
||||
import java.util.*;
|
||||
import java.lang.reflect.*;
|
||||
|
||||
/**
|
||||
* This program uses reflection to print all features of a class.
|
||||
* @version 1.11 2018-03-16
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ReflectionTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
throws ReflectiveOperationException
|
||||
{
|
||||
// read class name from command line args or user input
|
||||
String name;
|
||||
if (args.length > 0) name = args[0];
|
||||
else
|
||||
{
|
||||
var in = new Scanner(System.in);
|
||||
System.out.println("Enter class name (e.g. java.util.Date): ");
|
||||
name = in.next();
|
||||
}
|
||||
|
||||
// print class name and superclass name (if != Object)
|
||||
Class cl = Class.forName(name);
|
||||
Class supercl = cl.getSuperclass();
|
||||
String modifiers = Modifier.toString(cl.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.print("class " + name);
|
||||
if (supercl != null && supercl != Object.class) System.out.print(" extends "
|
||||
+ supercl.getName());
|
||||
|
||||
System.out.print("\n{\n");
|
||||
printConstructors(cl);
|
||||
System.out.println();
|
||||
printMethods(cl);
|
||||
System.out.println();
|
||||
printFields(cl);
|
||||
System.out.println("}");
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints all constructors of a class
|
||||
* @param cl a class
|
||||
*/
|
||||
public static void printConstructors(Class cl)
|
||||
{
|
||||
Constructor[] constructors = cl.getDeclaredConstructors();
|
||||
|
||||
for (Constructor c : constructors)
|
||||
{
|
||||
String name = c.getName();
|
||||
System.out.print(" ");
|
||||
String modifiers = Modifier.toString(c.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.print(name + "(");
|
||||
|
||||
// print parameter types
|
||||
Class[] paramTypes = c.getParameterTypes();
|
||||
for (int j = 0; j < paramTypes.length; j++)
|
||||
{
|
||||
if (j > 0) System.out.print(", ");
|
||||
System.out.print(paramTypes[j].getName());
|
||||
}
|
||||
System.out.println(");");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints all methods of a class
|
||||
* @param cl a class
|
||||
*/
|
||||
public static void printMethods(Class cl)
|
||||
{
|
||||
Method[] methods = cl.getDeclaredMethods();
|
||||
|
||||
for (Method m : methods)
|
||||
{
|
||||
Class retType = m.getReturnType();
|
||||
String name = m.getName();
|
||||
|
||||
System.out.print(" ");
|
||||
// print modifiers, return type and method name
|
||||
String modifiers = Modifier.toString(m.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.print(retType.getName() + " " + name + "(");
|
||||
|
||||
// print parameter types
|
||||
Class[] paramTypes = m.getParameterTypes();
|
||||
for (int j = 0; j < paramTypes.length; j++)
|
||||
{
|
||||
if (j > 0) System.out.print(", ");
|
||||
System.out.print(paramTypes[j].getName());
|
||||
}
|
||||
System.out.println(");");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints all fields of a class
|
||||
* @param cl a class
|
||||
*/
|
||||
public static void printFields(Class cl)
|
||||
{
|
||||
Field[] fields = cl.getDeclaredFields();
|
||||
|
||||
for (Field f : fields)
|
||||
{
|
||||
Class type = f.getType();
|
||||
String name = f.getName();
|
||||
System.out.print(" ");
|
||||
String modifiers = Modifier.toString(f.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.println(type.getName() + " " + name + ";");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package resources;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.5 2018-03-15
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ResourceTest
|
||||
{
|
||||
public static void main(String[] args) throws IOException
|
||||
{
|
||||
Class cl = ResourceTest.class;
|
||||
URL aboutURL = cl.getResource("about.gif");
|
||||
var icon = new ImageIcon(aboutURL);
|
||||
|
||||
InputStream stream = cl.getResourceAsStream("data/about.txt");
|
||||
var about = new String(stream.readAllBytes(), "UTF-8");
|
||||
|
||||
InputStream stream2 = cl.getResourceAsStream("/corejava/title.txt");
|
||||
var title = new String(stream2.readAllBytes(), StandardCharsets.UTF_8).trim();
|
||||
|
||||
JOptionPane.showMessageDialog(null, about, title, JOptionPane.INFORMATION_MESSAGE, icon);
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
Main-Class: resources.ResourceTest
|
||||
|
Before Width: | Height: | Size: 6.5 KiB |
@@ -1,5 +0,0 @@
|
||||
Core Java: Fundamentals
|
||||
11th Edition
|
||||
Cay Horstmann
|
||||
Copyright © 2018
|
||||
Prentice-Hall
|
||||
@@ -1 +0,0 @@
|
||||
serviceLoader.impl.CaesarCipher
|
||||
@@ -1,51 +0,0 @@
|
||||
package anonymousInnerClass;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.time.*;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates anonymous inner classes.
|
||||
* @version 1.12 2017-12-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class AnonymousInnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var clock = new TalkingClock();
|
||||
clock.start(1000, true);
|
||||
|
||||
// keep program running until the user selects "OK"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A clock that prints the time in regular intervals.
|
||||
*/
|
||||
class TalkingClock
|
||||
{
|
||||
/**
|
||||
* Starts the clock.
|
||||
* @param interval the interval between messages (in milliseconds)
|
||||
* @param beep true if the clock should beep
|
||||
*/
|
||||
public void start(int interval, boolean beep)
|
||||
{
|
||||
var listener = new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is "
|
||||
+ Instant.ofEpochMilli(event.getWhen()));
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
};
|
||||
var timer = new Timer(interval, listener);
|
||||
timer.start();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package clone;
|
||||
|
||||
/**
|
||||
* This program demonstrates cloning.
|
||||
* @version 1.11 2018-03-16
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CloneTest
|
||||
{
|
||||
public static void main(String[] args) throws CloneNotSupportedException
|
||||
{
|
||||
var original = new Employee("John Q. Public", 50000);
|
||||
original.setHireDay(2000, 1, 1);
|
||||
Employee copy = original.clone();
|
||||
copy.raiseSalary(10);
|
||||
copy.setHireDay(2002, 12, 31);
|
||||
System.out.println("original=" + original);
|
||||
System.out.println("copy=" + copy);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
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;
|
||||
hireDay = new Date();
|
||||
}
|
||||
|
||||
public Employee clone() throws CloneNotSupportedException
|
||||
{
|
||||
// call Object.clone()
|
||||
Employee cloned = (Employee) super.clone();
|
||||
|
||||
// clone mutable fields
|
||||
cloned.hireDay = (Date) hireDay.clone();
|
||||
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the hire day to a given date.
|
||||
* @param year the year of the hire day
|
||||
* @param month the month of the hire day
|
||||
* @param day the day of the hire day
|
||||
*/
|
||||
public void setHireDay(int year, int month, int day)
|
||||
{
|
||||
Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
|
||||
|
||||
// example of instance field mutation
|
||||
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 + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package innerClass;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.time.*;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of inner classes.
|
||||
* @version 1.11 2017-12-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class InnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var clock = new TalkingClock(1000, true);
|
||||
clock.start();
|
||||
|
||||
// keep program running until the user selects "OK"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A clock that prints the time in regular intervals.
|
||||
*/
|
||||
class TalkingClock
|
||||
{
|
||||
private int interval;
|
||||
private boolean beep;
|
||||
|
||||
/**
|
||||
* Constructs a talking clock
|
||||
* @param interval the interval between messages (in milliseconds)
|
||||
* @param beep true if the clock should beep
|
||||
*/
|
||||
public TalkingClock(int interval, boolean beep)
|
||||
{
|
||||
this.interval = interval;
|
||||
this.beep = beep;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the clock.
|
||||
*/
|
||||
public void start()
|
||||
{
|
||||
var listener = new TimePrinter();
|
||||
var timer = new Timer(interval, listener);
|
||||
timer.start();
|
||||
}
|
||||
|
||||
public class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is "
|
||||
+ Instant.ofEpochMilli(event.getWhen()));
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package interfaces;
|
||||
|
||||
public class Employee implements Comparable<Employee>
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
|
||||
public Employee(String name, double salary)
|
||||
{
|
||||
this.name = name;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares employees by salary
|
||||
* @param other another Employee object
|
||||
* @return a negative value if this employee has a lower salary than
|
||||
* otherObject, 0 if the salaries are the same, a positive value otherwise
|
||||
*/
|
||||
public int compareTo(Employee other)
|
||||
{
|
||||
return Double.compare(salary, other.salary);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package interfaces;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of the Comparable interface.
|
||||
* @version 1.30 2004-02-27
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EmployeeSortTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Harry Hacker", 35000);
|
||||
staff[1] = new Employee("Carl Cracker", 75000);
|
||||
staff[2] = new Employee("Tony Tester", 38000);
|
||||
|
||||
Arrays.sort(staff);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package lambda;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.Timer;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of lambda expressions.
|
||||
* @version 1.0 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LambdaTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
|
||||
"Jupiter", "Saturn", "Uranus", "Neptune" };
|
||||
System.out.println(Arrays.toString(planets));
|
||||
System.out.println("Sorted in dictionary order:");
|
||||
Arrays.sort(planets);
|
||||
System.out.println(Arrays.toString(planets));
|
||||
System.out.println("Sorted by length:");
|
||||
Arrays.sort(planets, (first, second) -> first.length() - second.length());
|
||||
System.out.println(Arrays.toString(planets));
|
||||
|
||||
var timer = new Timer(1000, event ->
|
||||
System.out.println("The time is " + new Date()));
|
||||
timer.start();
|
||||
|
||||
// keep program running until user selects "OK"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package localInnerClass;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.time.*;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of local inner classes.
|
||||
* @version 1.02 2017-12-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LocalInnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var clock = new TalkingClock();
|
||||
clock.start(1000, true);
|
||||
|
||||
// keep program running until the user selects "Ok"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A clock that prints the time in regular intervals.
|
||||
*/
|
||||
class TalkingClock
|
||||
{
|
||||
/**
|
||||
* Starts the clock.
|
||||
* @param interval the interval between messages (in milliseconds)
|
||||
* @param beep true if the clock should beep
|
||||
*/
|
||||
public void start(int interval, boolean beep)
|
||||
{
|
||||
class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is "
|
||||
+ Instant.ofEpochMilli(event.getWhen()));
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
var listener = new TimePrinter();
|
||||
var timer = new Timer(interval, listener);
|
||||
timer.start();
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package proxy;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of proxies.
|
||||
* @version 1.01 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ProxyTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var elements = new Object[1000];
|
||||
|
||||
// fill elements with proxies for the integers 1 . . . 1000
|
||||
for (int i = 0; i < elements.length; i++)
|
||||
{
|
||||
Integer value = i + 1;
|
||||
var handler = new TraceHandler(value);
|
||||
Object proxy = Proxy.newProxyInstance(
|
||||
ClassLoader.getSystemClassLoader(),
|
||||
new Class[] { Comparable.class } , handler);
|
||||
elements[i] = proxy;
|
||||
}
|
||||
|
||||
// construct a random integer
|
||||
Integer key = new Random().nextInt(elements.length) + 1;
|
||||
|
||||
// search for the key
|
||||
int result = Arrays.binarySearch(elements, key);
|
||||
|
||||
// print match if found
|
||||
if (result >= 0) System.out.println(elements[result]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An invocation handler that prints out the method name and parameters, then
|
||||
* invokes the original method
|
||||
*/
|
||||
class TraceHandler implements InvocationHandler
|
||||
{
|
||||
private Object target;
|
||||
|
||||
/**
|
||||
* Constructs a TraceHandler
|
||||
* @param t the implicit parameter of the method call
|
||||
*/
|
||||
public TraceHandler(Object t)
|
||||
{
|
||||
target = t;
|
||||
}
|
||||
|
||||
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
|
||||
{
|
||||
// print implicit argument
|
||||
System.out.print(target);
|
||||
// print method name
|
||||
System.out.print("." + m.getName() + "(");
|
||||
// print explicit arguments
|
||||
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(")");
|
||||
|
||||
// invoke actual method
|
||||
return m.invoke(target, args);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package serviceLoader;
|
||||
|
||||
public interface Cipher
|
||||
{
|
||||
byte[] encrypt(byte[] source, byte[] key);
|
||||
byte[] decrypt(byte[] source, byte[] key);
|
||||
int strength();
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package serviceLoader;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @version 1.01 2018-03-17
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
|
||||
public class ServiceLoaderTest
|
||||
{
|
||||
public static ServiceLoader<Cipher> cipherLoader
|
||||
= ServiceLoader.load(Cipher.class);
|
||||
|
||||
public static void main(String[] args) throws UnsupportedEncodingException
|
||||
{
|
||||
Cipher cipher = getCipher(1);
|
||||
var message = "Meet me at the toga party.";
|
||||
byte[] bytes = cipher.encrypt(message.getBytes(), new byte[] { 3 });
|
||||
var encrypted = new String(bytes, StandardCharsets.UTF_8);
|
||||
System.out.println(encrypted);
|
||||
}
|
||||
|
||||
public static Cipher getCipher(int minStrength)
|
||||
{
|
||||
for (Cipher cipher : cipherLoader)
|
||||
// Implicitly calls iterator
|
||||
if (cipher.strength() >= minStrength) return cipher;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package serviceLoader.impl;
|
||||
|
||||
import serviceLoader.Cipher;
|
||||
|
||||
public class CaesarCipher implements Cipher
|
||||
{
|
||||
public byte[] encrypt(byte[] source, byte[] key)
|
||||
{
|
||||
var result = new byte[source.length];
|
||||
for (int i = 0; i < source.length; i++)
|
||||
result[i] = (byte) (source[i] + key[0]);
|
||||
return result;
|
||||
}
|
||||
|
||||
public byte[] decrypt(byte[] source, byte[] key)
|
||||
{
|
||||
return encrypt(source, new byte[] { (byte) -key[0] });
|
||||
}
|
||||
|
||||
public int strength()
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package staticInnerClass;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of static inner classes.
|
||||
* @version 1.02 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class StaticInnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var values = new double[20];
|
||||
for (int i = 0; i < values.length; i++)
|
||||
values[i] = 100 * Math.random();
|
||||
ArrayAlg.Pair p = ArrayAlg.minmax(values);
|
||||
System.out.println("min = " + p.getFirst());
|
||||
System.out.println("max = " + p.getSecond());
|
||||
}
|
||||
}
|
||||
|
||||
class ArrayAlg
|
||||
{
|
||||
/**
|
||||
* A pair of floating-point numbers
|
||||
*/
|
||||
public static class Pair
|
||||
{
|
||||
private double first;
|
||||
private double second;
|
||||
|
||||
/**
|
||||
* Constructs a pair from two floating-point numbers
|
||||
* @param f the first number
|
||||
* @param s the second number
|
||||
*/
|
||||
public Pair(double f, double s)
|
||||
{
|
||||
first = f;
|
||||
second = s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first number of the pair
|
||||
* @return the first number
|
||||
*/
|
||||
public double getFirst()
|
||||
{
|
||||
return first;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the second number of the pair
|
||||
* @return the second number
|
||||
*/
|
||||
public double getSecond()
|
||||
{
|
||||
return second;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes both the minimum and the maximum of an array
|
||||
* @param values an array of floating-point numbers
|
||||
* @return a pair whose first element is the minimum and whose second element
|
||||
* is the maximum
|
||||
*/
|
||||
public static Pair minmax(double[] values)
|
||||
{
|
||||
double min = Double.POSITIVE_INFINITY;
|
||||
double max = Double.NEGATIVE_INFINITY;
|
||||
for (double v : values)
|
||||
{
|
||||
if (min > v) min = v;
|
||||
if (max < v) max = v;
|
||||
}
|
||||
return new Pair(min, max);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package timer;
|
||||
|
||||
/**
|
||||
@version 1.02 2017-12-14
|
||||
@author Cay Horstmann
|
||||
*/
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.time.*;
|
||||
import javax.swing.*;
|
||||
|
||||
public class TimerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var listener = new TimePrinter();
|
||||
|
||||
// construct a timer that calls the listener
|
||||
// once every second
|
||||
var timer = new Timer(1000, listener);
|
||||
timer.start();
|
||||
|
||||
// keep program running until the user selects "OK"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is "
|
||||
+ Instant.ofEpochMilli(event.getWhen()));
|
||||
Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
@@ -1,57 +0,0 @@
|
||||
package except;
|
||||
|
||||
import java.nio.charset.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
* @version 1.40 2018-03-17
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ExceptTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int thousand = 1000;
|
||||
double[] a = { 1000, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
performAction("Integer divide by zero", () -> 1 / (a.length - a.length));
|
||||
|
||||
performAction("Floating point divide by zero",
|
||||
() -> a[2] / (a[3] - a[3]));
|
||||
|
||||
performAction("Integer overflow",
|
||||
() -> thousand * thousand * thousand * thousand);
|
||||
|
||||
performAction("Square root of negative number", () -> Math.sqrt(-1));
|
||||
|
||||
performAction("Array index out of bounds", () -> a[1] - a[100]);
|
||||
|
||||
performAction("Bad cast", () -> (int[]) (Object) a);
|
||||
|
||||
performAction("Null pointer",
|
||||
() -> System.getProperty("woozle").toString());
|
||||
|
||||
performAction("No such file",
|
||||
() -> new Scanner(Paths.get("woozle.txt"), StandardCharsets.UTF_8).next());
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the given action and reports the result or failure.
|
||||
* @param description the description of the action
|
||||
* @param action the action to be carried out
|
||||
*/
|
||||
private static void performAction(String description,
|
||||
Callable<Object> action)
|
||||
{
|
||||
System.out.println(description);
|
||||
try
|
||||
{
|
||||
System.out.println(action.call());
|
||||
}
|
||||
catch (Throwable t)
|
||||
{
|
||||
System.out.println(t.getClass().getName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package exceptional;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @version 1.12 2017-12-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ExceptionalTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int i = 0;
|
||||
int ntry = 10000000;
|
||||
var stack = new Stack<String>();
|
||||
|
||||
// test a stack for emptiness ntry times
|
||||
System.out.println("Testing for empty stack");
|
||||
long start = System.currentTimeMillis();
|
||||
for (i = 0; i <= ntry; i++)
|
||||
if (!stack.empty()) stack.pop();
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println((end - start) + " milliseconds");
|
||||
|
||||
// pop an empty stack ntry times and catch the resulting exception
|
||||
System.out.println("Catching EmptyStackException");
|
||||
start = System.currentTimeMillis();
|
||||
for (i = 0; i <= ntry; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
stack.pop();
|
||||
}
|
||||
catch (EmptyStackException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println((end - start) + " milliseconds");
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
package logging;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.io.*;
|
||||
import java.util.logging.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A modification of the image viewer program that logs various events.
|
||||
* @version 1.03 2015-08-20
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LoggingImageViewer
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
if (System.getProperty("java.util.logging.config.class") == null
|
||||
&& System.getProperty("java.util.logging.config.file") == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);
|
||||
final int LOG_ROTATION_COUNT = 10;
|
||||
var handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
|
||||
Logger.getLogger("com.horstmann.corejava").addHandler(handler);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
|
||||
"Can't create log file handler", e);
|
||||
}
|
||||
}
|
||||
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
var windowHandler = new WindowHandler();
|
||||
windowHandler.setLevel(Level.ALL);
|
||||
Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
|
||||
|
||||
var frame = new ImageViewerFrame();
|
||||
frame.setTitle("LoggingImageViewer");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
|
||||
Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The frame that shows the image.
|
||||
*/
|
||||
class ImageViewerFrame extends JFrame
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
private JLabel label;
|
||||
private static Logger logger = Logger.getLogger("com.horstmann.corejava");
|
||||
|
||||
public ImageViewerFrame()
|
||||
{
|
||||
logger.entering("ImageViewerFrame", "<init>");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// set up menu bar
|
||||
var menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
|
||||
var menu = new JMenu("File");
|
||||
menuBar.add(menu);
|
||||
|
||||
var openItem = new JMenuItem("Open");
|
||||
menu.add(openItem);
|
||||
openItem.addActionListener(new FileOpenListener());
|
||||
|
||||
var exitItem = new JMenuItem("Exit");
|
||||
menu.add(exitItem);
|
||||
exitItem.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
logger.fine("Exiting.");
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
|
||||
// use a label to display the images
|
||||
label = new JLabel();
|
||||
add(label);
|
||||
logger.exiting("ImageViewerFrame", "<init>");
|
||||
}
|
||||
|
||||
private class FileOpenListener implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);
|
||||
|
||||
// set up file chooser
|
||||
var chooser = new JFileChooser();
|
||||
chooser.setCurrentDirectory(new File("."));
|
||||
|
||||
// accept all files ending with .gif
|
||||
chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
|
||||
{
|
||||
public boolean accept(File f)
|
||||
{
|
||||
return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
|
||||
}
|
||||
|
||||
public String getDescription()
|
||||
{
|
||||
return "GIF Images";
|
||||
}
|
||||
});
|
||||
|
||||
// show file chooser dialog
|
||||
int r = chooser.showOpenDialog(ImageViewerFrame.this);
|
||||
|
||||
// if image file accepted, set it as icon of the label
|
||||
if (r == JFileChooser.APPROVE_OPTION)
|
||||
{
|
||||
String name = chooser.getSelectedFile().getPath();
|
||||
logger.log(Level.FINE, "Reading file {0}", name);
|
||||
label.setIcon(new ImageIcon(name));
|
||||
}
|
||||
else logger.fine("File open dialog canceled.");
|
||||
logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler for displaying log records in a window.
|
||||
*/
|
||||
class WindowHandler extends StreamHandler
|
||||
{
|
||||
private JFrame frame;
|
||||
|
||||
public WindowHandler()
|
||||
{
|
||||
frame = new JFrame();
|
||||
var output = new JTextArea();
|
||||
output.setEditable(false);
|
||||
frame.setSize(200, 200);
|
||||
frame.add(new JScrollPane(output));
|
||||
frame.setFocusableWindowState(false);
|
||||
frame.setVisible(true);
|
||||
setOutputStream(new OutputStream()
|
||||
{
|
||||
public void write(int b)
|
||||
{
|
||||
} // not called
|
||||
|
||||
public void write(byte[] b, int off, int len)
|
||||
{
|
||||
output.append(new String(b, off, len));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void publish(LogRecord record)
|
||||
{
|
||||
if (!frame.isVisible()) return;
|
||||
super.publish(record);
|
||||
flush();
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
package loggingfx;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import javafx.application.*;
|
||||
import javafx.scene.*;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.control.Alert.*;
|
||||
import javafx.scene.image.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.*;
|
||||
import javafx.stage.FileChooser.*;
|
||||
|
||||
/**
|
||||
* A modification of the image viewer program that logs various events.
|
||||
* @version 1.10 2017-12-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LoggingImageViewer extends Application
|
||||
{
|
||||
private static final int MIN_SIZE = 400;
|
||||
private Logger logger = Logger.getLogger("com.horstmann.corejava");
|
||||
|
||||
public void start(Stage stage) throws IOException
|
||||
{
|
||||
if (System.getProperty("java.util.logging.config.class") == null
|
||||
&& System.getProperty("java.util.logging.config.file") == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.setLevel(Level.ALL);
|
||||
final int LOG_ROTATION_COUNT = 10;
|
||||
Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0,
|
||||
LOG_ROTATION_COUNT);
|
||||
logger.addHandler(handler);
|
||||
handler.setLevel(Level.ALL);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
logger.log(Level.SEVERE, "Can't create log file handler", e);
|
||||
}
|
||||
}
|
||||
|
||||
BorderPane pane = new BorderPane();
|
||||
MenuBar bar = new MenuBar();
|
||||
pane.setTop(bar);
|
||||
Menu fileMenu = new Menu("File");
|
||||
bar.getMenus().add(fileMenu);
|
||||
MenuItem openItem = new MenuItem("Open");
|
||||
openItem.setOnAction(event -> load(stage, pane));
|
||||
MenuItem exitItem = new MenuItem("Exit");
|
||||
exitItem.setOnAction(event -> Platform.exit());
|
||||
fileMenu.getItems().addAll(openItem, exitItem);
|
||||
stage.setScene(new Scene(pane, MIN_SIZE, MIN_SIZE));
|
||||
stage.setTitle("ImageViewer");
|
||||
|
||||
logger.addHandler(new WindowHandler(stage, Level.ALL));
|
||||
logger.fine("Showing stage");
|
||||
stage.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads an image.
|
||||
* @param stage the stage above which to place the file chooser
|
||||
* @param pane the pane into which to place the image view
|
||||
*/
|
||||
public void load(Stage stage, BorderPane pane)
|
||||
{
|
||||
logger.entering("LoggingImageViewerFrame", "load",
|
||||
new Object[] { stage, pane });
|
||||
FileChooser fileChooser = new FileChooser();
|
||||
fileChooser.getExtensionFilters().addAll(
|
||||
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
|
||||
new ExtensionFilter("All Files", "*.*"));
|
||||
File file = fileChooser.showOpenDialog(stage);
|
||||
logger.fine("Selected file: " + file);
|
||||
if (file != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
Path path = file.toPath();
|
||||
Image image = new Image(Files.newInputStream(path));
|
||||
pane.setCenter(new ImageView(image));
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
logger.log(Level.FINE, "File not found", e);
|
||||
Alert alert = new Alert(AlertType.ERROR,
|
||||
"Cannot open file.");
|
||||
alert.showAndWait();
|
||||
}
|
||||
}
|
||||
logger.exiting("LoggingImageViewerFrame", "load");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler for displaying log records in a window.
|
||||
*/
|
||||
class WindowHandler extends StreamHandler
|
||||
{
|
||||
public WindowHandler(Stage parent, Level level)
|
||||
{
|
||||
setLevel(level);
|
||||
TextArea output = new TextArea();
|
||||
output.setEditable(false);
|
||||
Stage stage = new Stage();
|
||||
stage.setScene(new Scene(output, 400, 200));
|
||||
stage.setTitle("Log messages");
|
||||
stage.setX(100);
|
||||
stage.setY(100);
|
||||
|
||||
stage.show();
|
||||
setOutputStream(new OutputStream()
|
||||
{
|
||||
public void write(int b)
|
||||
{
|
||||
// not called
|
||||
}
|
||||
|
||||
public void write(byte[] b, int off, int len)
|
||||
{
|
||||
output.appendText(new String(b, off, len));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void publish(LogRecord record)
|
||||
{
|
||||
super.publish(record);
|
||||
flush();
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package stackTrace;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A program that displays a trace feature of a recursive method call.
|
||||
* @version 1.10 2017-12-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class StackTraceTest
|
||||
{
|
||||
/**
|
||||
* Computes the factorial of a number
|
||||
* @param n a non-negative integer
|
||||
* @return n! = 1 * 2 * . . . * n
|
||||
*/
|
||||
public static int factorial(int n)
|
||||
{
|
||||
System.out.println("factorial(" + n + "):");
|
||||
var walker = StackWalker.getInstance();
|
||||
walker.forEach(System.out::println);
|
||||
int r;
|
||||
if (n <= 1) r = 1;
|
||||
else r = n * factorial(n - 1);
|
||||
System.out.println("return " + r);
|
||||
return r;
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
try (var in = new Scanner(System.in))
|
||||
{
|
||||
System.out.print("Enter n: ");
|
||||
int n = in.nextInt();
|
||||
factorial(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package genericAlgorithms;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
|
||||
/**
|
||||
* @version 1.00 2015-05-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class GenericAlgorithms
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Pair<String> p = Pair.makePair(String::new);
|
||||
System.out.println(p);
|
||||
|
||||
p = Pair.makePair(String.class);
|
||||
System.out.println(p);
|
||||
|
||||
String[] ss = ArrayAlg.minmax("Tom", "Dick", "Harry");
|
||||
System.out.println(Arrays.toString(ss));
|
||||
|
||||
ss = ArrayAlg.minmax(String[]::new, "Tom", "Dick", "Harry");
|
||||
System.out.println(Arrays.toString(ss));
|
||||
}
|
||||
}
|
||||
|
||||
class ArrayAlg
|
||||
{
|
||||
public static <T extends Comparable> T[] minmax(IntFunction<T[]> constr, T... a)
|
||||
{
|
||||
T[] mm = constr.apply(2);
|
||||
T min = a[0];
|
||||
T max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.compareTo(a[i]) > 0) min = a[i];
|
||||
if (max.compareTo(a[i]) < 0) max = a[i];
|
||||
}
|
||||
return mm;
|
||||
}
|
||||
|
||||
public static <T extends Comparable> T[] minmax(T... a)
|
||||
{
|
||||
T[] mm = (T[]) Array.newInstance(a.getClass().getComponentType(), 2);
|
||||
T min = a[0];
|
||||
T max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.compareTo(a[i]) > 0) min = a[i];
|
||||
if (max.compareTo(a[i]) < 0) max = a[i];
|
||||
}
|
||||
return (T[]) mm; // compiles with warning
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
package genericAlgorithms;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* @version 1.00 2004-05-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Pair<T>
|
||||
{
|
||||
private T first;
|
||||
private T second;
|
||||
|
||||
public Pair() { first = null; second = null; }
|
||||
public Pair(T first, T second) { this.first = first; this.second = second; }
|
||||
|
||||
public T getFirst() { return first; }
|
||||
public T getSecond() { return second; }
|
||||
|
||||
public void setFirst(T newValue) { first = newValue; }
|
||||
public void setSecond(T newValue) { second = newValue; }
|
||||
|
||||
public String toString() { return "(" + first + ", " + second + ")"; }
|
||||
|
||||
public static <T> Pair<T> makePair(Supplier<T> constr)
|
||||
{
|
||||
return new Pair<>(constr.get(), constr.get());
|
||||
}
|
||||
|
||||
public static <T> Pair<T> makePair(Class<T> cl)
|
||||
{
|
||||
try {
|
||||
return new Pair<>(cl.getConstructor().newInstance(),
|
||||
cl.getConstructor().newInstance());
|
||||
}
|
||||
catch (Exception e) { return null; }
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
package genericReflection;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @version 1.11 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class GenericReflectionTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// read class name from command line args or user input
|
||||
String name;
|
||||
if (args.length > 0) name = args[0];
|
||||
else
|
||||
{
|
||||
try (var in = new Scanner(System.in))
|
||||
{
|
||||
System.out.println("Enter class name (e.g., java.util.Collections): ");
|
||||
name = in.next();
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// print generic info for class and public methods
|
||||
Class<?> cl = Class.forName(name);
|
||||
printClass(cl);
|
||||
for (Method m : cl.getDeclaredMethods())
|
||||
printMethod(m);
|
||||
}
|
||||
catch (ClassNotFoundException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void printClass(Class<?> cl)
|
||||
{
|
||||
System.out.print(cl);
|
||||
printTypes(cl.getTypeParameters(), "<", ", ", ">", true);
|
||||
Type sc = cl.getGenericSuperclass();
|
||||
if (sc != null)
|
||||
{
|
||||
System.out.print(" extends ");
|
||||
printType(sc, false);
|
||||
}
|
||||
printTypes(cl.getGenericInterfaces(), " implements ", ", ", "", false);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static void printMethod(Method m)
|
||||
{
|
||||
String name = m.getName();
|
||||
System.out.print(Modifier.toString(m.getModifiers()));
|
||||
System.out.print(" ");
|
||||
printTypes(m.getTypeParameters(), "<", ", ", "> ", true);
|
||||
|
||||
printType(m.getGenericReturnType(), false);
|
||||
System.out.print(" ");
|
||||
System.out.print(name);
|
||||
System.out.print("(");
|
||||
printTypes(m.getGenericParameterTypes(), "", ", ", "", false);
|
||||
System.out.println(")");
|
||||
}
|
||||
|
||||
public static void printTypes(Type[] types, String pre, String sep, String suf,
|
||||
boolean isDefinition)
|
||||
{
|
||||
if (pre.equals(" extends ") && Arrays.equals(types, new Type[] { Object.class }))
|
||||
return;
|
||||
if (types.length > 0) System.out.print(pre);
|
||||
for (int i = 0; i < types.length; i++)
|
||||
{
|
||||
if (i > 0) System.out.print(sep);
|
||||
printType(types[i], isDefinition);
|
||||
}
|
||||
if (types.length > 0) System.out.print(suf);
|
||||
}
|
||||
|
||||
public static void printType(Type type, boolean isDefinition)
|
||||
{
|
||||
if (type instanceof Class)
|
||||
{
|
||||
var t = (Class<?>) type;
|
||||
System.out.print(t.getName());
|
||||
}
|
||||
else if (type instanceof TypeVariable)
|
||||
{
|
||||
var t = (TypeVariable<?>) type;
|
||||
System.out.print(t.getName());
|
||||
if (isDefinition)
|
||||
printTypes(t.getBounds(), " extends ", " & ", "", false);
|
||||
}
|
||||
else if (type instanceof WildcardType)
|
||||
{
|
||||
var t = (WildcardType) type;
|
||||
System.out.print("?");
|
||||
printTypes(t.getUpperBounds(), " extends ", " & ", "", false);
|
||||
printTypes(t.getLowerBounds(), " super ", " & ", "", false);
|
||||
}
|
||||
else if (type instanceof ParameterizedType)
|
||||
{
|
||||
var t = (ParameterizedType) type;
|
||||
Type owner = t.getOwnerType();
|
||||
if (owner != null)
|
||||
{
|
||||
printType(owner, false);
|
||||
System.out.print(".");
|
||||
}
|
||||
printType(t.getRawType(), false);
|
||||
printTypes(t.getActualTypeArguments(), "<", ", ", ">", false);
|
||||
}
|
||||
else if (type instanceof GenericArrayType)
|
||||
{
|
||||
var t = (GenericArrayType) type;
|
||||
System.out.print("");
|
||||
printType(t.getGenericComponentType(), isDefinition);
|
||||
System.out.print("[]");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package genericReflection;
|
||||
|
||||
/**
|
||||
@version 1.01 2018-04-10
|
||||
@author Cay Horstmann
|
||||
*/
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
|
||||
/**
|
||||
* A type literal describes a type that can be generic, such as
|
||||
* ArrayList<String>.
|
||||
*/
|
||||
class TypeLiteral<T>
|
||||
{
|
||||
private Type type;
|
||||
|
||||
/**
|
||||
* This constructor must be invoked from an anonymous subclass
|
||||
* as new TypeLiteral<. . .>(){}.
|
||||
*/
|
||||
public TypeLiteral()
|
||||
{
|
||||
Type parentType = getClass().getGenericSuperclass();
|
||||
if (parentType instanceof ParameterizedType)
|
||||
{
|
||||
type = ((ParameterizedType) parentType).getActualTypeArguments()[0];
|
||||
}
|
||||
else
|
||||
throw new UnsupportedOperationException(
|
||||
"Construct as new TypeLiteral<. . .>(){}");
|
||||
}
|
||||
|
||||
private TypeLiteral(Type type)
|
||||
{
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Yields a type literal that describes the given type.
|
||||
*/
|
||||
public static TypeLiteral<?> of(Type type)
|
||||
{
|
||||
return new TypeLiteral<Object>(type);
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
if (type instanceof Class) return ((Class<?>) type).getName();
|
||||
else return type.toString();
|
||||
}
|
||||
|
||||
public boolean equals(Object otherObject)
|
||||
{
|
||||
return otherObject instanceof TypeLiteral
|
||||
&& type.equals(((TypeLiteral<?>) otherObject).type);
|
||||
}
|
||||
|
||||
public int hashCode()
|
||||
{
|
||||
return type.hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats objects, using rules that associate types with formatting functions.
|
||||
*/
|
||||
class Formatter
|
||||
{
|
||||
private Map<TypeLiteral<?>, Function<?, String>> rules = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Add a formatting rule to this formatter.
|
||||
* @param type the type to which this rule applies
|
||||
* @param formatterForType the function that formats objects of this type
|
||||
*/
|
||||
public <T> void forType(TypeLiteral<T> type, Function<T, String> formatterForType)
|
||||
{
|
||||
rules.put(type, formatterForType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats all fields of an object using the rules of this formatter.
|
||||
* @param obj an object
|
||||
* @return a string with all field names and formatted values
|
||||
*/
|
||||
public String formatFields(Object obj)
|
||||
throws IllegalArgumentException, IllegalAccessException
|
||||
{
|
||||
var result = new StringBuilder();
|
||||
for (Field f : obj.getClass().getDeclaredFields())
|
||||
{
|
||||
result.append(f.getName());
|
||||
result.append("=");
|
||||
f.setAccessible(true);
|
||||
Function<?, String> formatterForType = rules.get(TypeLiteral.of(f.getGenericType()));
|
||||
if (formatterForType != null)
|
||||
{
|
||||
// formatterForType has parameter type ?. Nothing can be passed to its apply
|
||||
// method. Cast makes the parameter type to Object so we can invoke it.
|
||||
@SuppressWarnings("unchecked")
|
||||
Function<Object, String> objectFormatter
|
||||
= (Function<Object, String>) formatterForType;
|
||||
result.append(objectFormatter.apply(f.get(obj)));
|
||||
}
|
||||
else
|
||||
result.append(f.get(obj).toString());
|
||||
result.append("\n");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public class TypeLiterals
|
||||
{
|
||||
public static class Sample
|
||||
{
|
||||
ArrayList<Integer> nums;
|
||||
ArrayList<Character> chars;
|
||||
ArrayList<String> strings;
|
||||
public Sample()
|
||||
{
|
||||
nums = new ArrayList<>();
|
||||
nums.add(42); nums.add(1729);
|
||||
chars = new ArrayList<>();
|
||||
chars.add('H'); chars.add('i');
|
||||
strings = new ArrayList<>();
|
||||
strings.add("Hello"); strings.add("World");
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> String join(String separator, ArrayList<T> elements)
|
||||
{
|
||||
var result = new StringBuilder();
|
||||
for (T e : elements)
|
||||
{
|
||||
if (result.length() > 0) result.append(separator);
|
||||
result.append(e.toString());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception
|
||||
{
|
||||
var formatter = new Formatter();
|
||||
formatter.forType(new TypeLiteral<ArrayList<Integer>>(){},
|
||||
lst -> join(" ", lst));
|
||||
formatter.forType(new TypeLiteral<ArrayList<Character>>(){},
|
||||
lst -> "\"" + join("", lst) + "\"");
|
||||
System.out.println(formatter.formatFields(new Sample()));
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package limitations;
|
||||
|
||||
interface Task
|
||||
{
|
||||
void run() throws Exception;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T extends Throwable> void throwAs(Throwable t) throws T
|
||||
{
|
||||
throw (T) t;
|
||||
}
|
||||
|
||||
static Runnable asRunnable(Task task)
|
||||
{
|
||||
return () ->
|
||||
{
|
||||
try
|
||||
{
|
||||
task.run();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Task.<RuntimeException>throwAs(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class DefeatCheckedExceptionChecking
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var thread = new Thread(Task.asRunnable(() ->
|
||||
{
|
||||
Thread.sleep(1000);
|
||||
System.out.println("Hello, World!");
|
||||
throw new Exception("Check this out!");
|
||||
}));
|
||||
thread.start();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package limitations;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class NoGenericArray
|
||||
{
|
||||
public static <T extends Comparable> T[] minmax(T... a)
|
||||
{
|
||||
var mm = new Comparable[2];
|
||||
T min = a[0];
|
||||
T max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.compareTo(a[i]) > 0) min = a[i];
|
||||
if (max.compareTo(a[i]) < 0) max = a[i];
|
||||
}
|
||||
mm[0] = min;
|
||||
mm[1] = max;
|
||||
return (T[]) mm; // compiles with warning
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
String[] fl = minmax("Tom", "Dick", "Harry");
|
||||
System.out.println(Arrays.toString(fl));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package pair1;
|
||||
|
||||
/**
|
||||
* @version 1.00 2004-05-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Pair<T>
|
||||
{
|
||||
private T first;
|
||||
private T second;
|
||||
|
||||
public Pair() { first = null; second = null; }
|
||||
public Pair(T first, T second) { this.first = first; this.second = second; }
|
||||
|
||||
public T getFirst() { return first; }
|
||||
public T getSecond() { return second; }
|
||||
|
||||
public void setFirst(T newValue) { first = newValue; }
|
||||
public void setSecond(T newValue) { second = newValue; }
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package pair1;
|
||||
|
||||
/**
|
||||
* @version 1.01 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PairTest1
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
String[] words = { "Mary", "had", "a", "little", "lamb" };
|
||||
Pair<String> mm = ArrayAlg.minmax(words);
|
||||
System.out.println("min = " + mm.getFirst());
|
||||
System.out.println("max = " + mm.getSecond());
|
||||
}
|
||||
}
|
||||
|
||||
class ArrayAlg
|
||||
{
|
||||
/**
|
||||
* Gets the minimum and maximum of an array of strings.
|
||||
* @param a an array of strings
|
||||
* @return a pair with the min and max values, or null if a is null or empty
|
||||
*/
|
||||
public static Pair<String> minmax(String[] a)
|
||||
{
|
||||
if (a == null || a.length == 0) return null;
|
||||
String min = a[0];
|
||||
String max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.compareTo(a[i]) > 0) min = a[i];
|
||||
if (max.compareTo(a[i]) < 0) max = a[i];
|
||||
}
|
||||
return new Pair<>(min, max);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package pair2;
|
||||
|
||||
/**
|
||||
* @version 1.00 2004-05-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Pair<T>
|
||||
{
|
||||
private T first;
|
||||
private T second;
|
||||
|
||||
public Pair() { first = null; second = null; }
|
||||
public Pair(T first, T second) { this.first = first; this.second = second; }
|
||||
|
||||
public T getFirst() { return first; }
|
||||
public T getSecond() { return second; }
|
||||
|
||||
public void setFirst(T newValue) { first = newValue; }
|
||||
public void setSecond(T newValue) { second = newValue; }
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package pair2;
|
||||
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* @version 1.02 2015-06-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PairTest2
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
LocalDate[] birthdays =
|
||||
{
|
||||
LocalDate.of(1906, 12, 9), // G. Hopper
|
||||
LocalDate.of(1815, 12, 10), // A. Lovelace
|
||||
LocalDate.of(1903, 12, 3), // J. von Neumann
|
||||
LocalDate.of(1910, 6, 22), // K. Zuse
|
||||
};
|
||||
Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
|
||||
System.out.println("min = " + mm.getFirst());
|
||||
System.out.println("max = " + mm.getSecond());
|
||||
}
|
||||
}
|
||||
|
||||
class ArrayAlg
|
||||
{
|
||||
/**
|
||||
Gets the minimum and maximum of an array of objects of type T.
|
||||
@param a an array of objects of type T
|
||||
@return a pair with the min and max values, or null if a is null or empty
|
||||
*/
|
||||
public static <T extends Comparable> Pair<T> minmax(T[] a)
|
||||
{
|
||||
if (a == null || a.length == 0) return null;
|
||||
T min = a[0];
|
||||
T max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.compareTo(a[i]) > 0) min = a[i];
|
||||
if (max.compareTo(a[i]) < 0) max = a[i];
|
||||
}
|
||||
return new Pair<>(min, max);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package pair3;
|
||||
|
||||
import java.time.*;
|
||||
|
||||
public class Employee
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package pair3;
|
||||
|
||||
public class Manager extends Employee
|
||||
{
|
||||
private double bonus;
|
||||
|
||||
/**
|
||||
@param name the employee's name
|
||||
@param salary the salary
|
||||
@param year the hire year
|
||||
@param month the hire month
|
||||
@param day the hire day
|
||||
*/
|
||||
public Manager(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
super(name, salary, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double b)
|
||||
{
|
||||
bonus = b;
|
||||
}
|
||||
|
||||
public double getBonus()
|
||||
{
|
||||
return bonus;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package pair3;
|
||||
|
||||
/**
|
||||
* @version 1.00 2004-05-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Pair<T>
|
||||
{
|
||||
private T first;
|
||||
private T second;
|
||||
|
||||
public Pair() { first = null; second = null; }
|
||||
public Pair(T first, T second) { this.first = first; this.second = second; }
|
||||
|
||||
public T getFirst() { return first; }
|
||||
public T getSecond() { return second; }
|
||||
|
||||
public void setFirst(T newValue) { first = newValue; }
|
||||
public void setSecond(T newValue) { second = newValue; }
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package pair3;
|
||||
|
||||
/**
|
||||
* @version 1.01 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PairTest3
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
|
||||
var cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
|
||||
var buddies = new Pair<Manager>(ceo, cfo);
|
||||
printBuddies(buddies);
|
||||
|
||||
ceo.setBonus(1000000);
|
||||
cfo.setBonus(500000);
|
||||
Manager[] managers = { ceo, cfo };
|
||||
|
||||
var result = new Pair<Employee>();
|
||||
minmaxBonus(managers, result);
|
||||
System.out.println("first: " + result.getFirst().getName()
|
||||
+ ", second: " + result.getSecond().getName());
|
||||
maxminBonus(managers, result);
|
||||
System.out.println("first: " + result.getFirst().getName()
|
||||
+ ", second: " + result.getSecond().getName());
|
||||
}
|
||||
|
||||
public static void printBuddies(Pair<? extends Employee> p)
|
||||
{
|
||||
Employee first = p.getFirst();
|
||||
Employee second = p.getSecond();
|
||||
System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
|
||||
}
|
||||
|
||||
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
|
||||
{
|
||||
if (a.length == 0) return;
|
||||
Manager min = a[0];
|
||||
Manager max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.getBonus() > a[i].getBonus()) min = a[i];
|
||||
if (max.getBonus() < a[i].getBonus()) max = a[i];
|
||||
}
|
||||
result.setFirst(min);
|
||||
result.setSecond(max);
|
||||
}
|
||||
|
||||
public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
|
||||
{
|
||||
minmaxBonus(a, result);
|
||||
PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
|
||||
}
|
||||
// can't write public static <T super manager> . . .
|
||||
}
|
||||
|
||||
class PairAlg
|
||||
{
|
||||
public static boolean hasNulls(Pair<?> p)
|
||||
{
|
||||
return p.getFirst() == null || p.getSecond() == null;
|
||||
}
|
||||
|
||||
public static void swap(Pair<?> p) { swapHelper(p); }
|
||||
|
||||
public static <T> void swapHelper(Pair<T> p)
|
||||
{
|
||||
T t = p.getFirst();
|
||||
p.setFirst(p.getSecond());
|
||||
p.setSecond(t);
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 76 KiB |
@@ -1,123 +0,0 @@
|
||||
package circularArrayQueue;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates how to extend the collections framework.
|
||||
* @version 1.22 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CircularArrayQueueTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var q = new CircularArrayQueue<String>(5);
|
||||
q.add("Amy");
|
||||
q.add("Bob");
|
||||
q.add("Carl");
|
||||
q.add("Deedee");
|
||||
q.add("Emile");
|
||||
q.remove();
|
||||
q.add("Fifi");
|
||||
q.remove();
|
||||
for (String s : q) System.out.println(s);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
A first-in, first-out bounded collection.
|
||||
*/
|
||||
class CircularArrayQueue<E> extends AbstractQueue<E>
|
||||
{
|
||||
private Object[] elements;
|
||||
private int head;
|
||||
private int tail;
|
||||
private int count;
|
||||
private int modcount;
|
||||
|
||||
/**
|
||||
Constructs an empty queue.
|
||||
@param capacity the maximum capacity of the queue
|
||||
*/
|
||||
public CircularArrayQueue(int capacity)
|
||||
{
|
||||
elements = new Object[capacity];
|
||||
count = 0;
|
||||
head = 0;
|
||||
tail = 0;
|
||||
}
|
||||
|
||||
public boolean offer(E newElement)
|
||||
{
|
||||
assert newElement != null;
|
||||
if (count < elements.length)
|
||||
{
|
||||
elements[tail] = newElement;
|
||||
tail = (tail + 1) % elements.length;
|
||||
count++;
|
||||
modcount++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
public E poll()
|
||||
{
|
||||
if (count == 0) return null;
|
||||
E r = peek();
|
||||
head = (head + 1) % elements.length;
|
||||
count--;
|
||||
modcount++;
|
||||
return r;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public E peek()
|
||||
{
|
||||
if (count == 0) return null;
|
||||
return (E) elements[head];
|
||||
}
|
||||
|
||||
public int size()
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
public Iterator<E> iterator()
|
||||
{
|
||||
return new QueueIterator();
|
||||
}
|
||||
|
||||
private class QueueIterator implements Iterator<E>
|
||||
{
|
||||
private int offset;
|
||||
private int modcountAtConstruction;
|
||||
|
||||
public QueueIterator()
|
||||
{
|
||||
modcountAtConstruction = modcount;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public E next()
|
||||
{
|
||||
if (!hasNext()) throw new NoSuchElementException();
|
||||
var r = (E) elements[(head + offset) % elements.length];
|
||||
offset++;
|
||||
return r;
|
||||
}
|
||||
|
||||
public boolean hasNext()
|
||||
{
|
||||
if (modcount != modcountAtConstruction)
|
||||
throw new ConcurrentModificationException();
|
||||
return offset < count;
|
||||
}
|
||||
|
||||
public void remove()
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
@@ -1,59 +0,0 @@
|
||||
package linkedList;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates operations on linked lists.
|
||||
* @version 1.12 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LinkedListTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var a = new LinkedList<String>();
|
||||
a.add("Amy");
|
||||
a.add("Carl");
|
||||
a.add("Erica");
|
||||
|
||||
var b = new LinkedList<String>();
|
||||
b.add("Bob");
|
||||
b.add("Doug");
|
||||
b.add("Frances");
|
||||
b.add("Gloria");
|
||||
|
||||
// merge the words from b into a
|
||||
|
||||
ListIterator<String> aIter = a.listIterator();
|
||||
Iterator<String> bIter = b.iterator();
|
||||
|
||||
while (bIter.hasNext())
|
||||
{
|
||||
if (aIter.hasNext()) aIter.next();
|
||||
aIter.add(bIter.next());
|
||||
}
|
||||
|
||||
System.out.println(a);
|
||||
|
||||
// remove every second word from b
|
||||
|
||||
bIter = b.iterator();
|
||||
while (bIter.hasNext())
|
||||
{
|
||||
bIter.next(); // skip one element
|
||||
if (bIter.hasNext())
|
||||
{
|
||||
bIter.next(); // skip next element
|
||||
bIter.remove(); // remove that element
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(b);
|
||||
|
||||
// bulk operation: remove all words in b from a
|
||||
|
||||
a.removeAll(b);
|
||||
|
||||
System.out.println(a);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package map;
|
||||
|
||||
/**
|
||||
* A minimalist employee class for testing purposes.
|
||||
*/
|
||||
public class Employee
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
|
||||
/**
|
||||
* Constructs an employee with $0 salary.
|
||||
* @param n the employee name
|
||||
*/
|
||||
public Employee(String name)
|
||||
{
|
||||
this.name = name;
|
||||
salary = 0;
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return "[name=" + name + ", salary=" + salary + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package map;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of a map with key type String and value type Employee.
|
||||
* @version 1.12 2015-06-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class MapTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var staff = new HashMap<String, Employee>();
|
||||
staff.put("144-25-5464", new Employee("Amy Lee"));
|
||||
staff.put("567-24-2546", new Employee("Harry Hacker"));
|
||||
staff.put("157-62-7935", new Employee("Gary Cooper"));
|
||||
staff.put("456-62-5527", new Employee("Francesca Cruz"));
|
||||
|
||||
// print all entries
|
||||
|
||||
System.out.println(staff);
|
||||
|
||||
// remove an entry
|
||||
|
||||
staff.remove("567-24-2546");
|
||||
|
||||
// replace an entry
|
||||
|
||||
staff.put("456-62-5527", new Employee("Francesca Miller"));
|
||||
|
||||
// look up a value
|
||||
|
||||
System.out.println(staff.get("157-62-7935"));
|
||||
|
||||
// iterate through all entries
|
||||
|
||||
staff.forEach((k, v) ->
|
||||
System.out.println("key=" + k + ", value=" + v));
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package priorityQueue;
|
||||
|
||||
import java.util.*;
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of a priority queue.
|
||||
* @version 1.02 2015-06-20
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PriorityQueueTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var pq = new PriorityQueue<LocalDate>();
|
||||
pq.add(LocalDate.of(1906, 12, 9)); // G. Hopper
|
||||
pq.add(LocalDate.of(1815, 12, 10)); // A. Lovelace
|
||||
pq.add(LocalDate.of(1903, 12, 3)); // J. von Neumann
|
||||
pq.add(LocalDate.of(1910, 6, 22)); // K. Zuse
|
||||
|
||||
System.out.println("Iterating over elements . . .");
|
||||
for (LocalDate date : pq)
|
||||
System.out.println(date);
|
||||
System.out.println("Removing elements . . .");
|
||||
while (!pq.isEmpty())
|
||||
System.out.println(pq.remove());
|
||||
}
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
package properties;
|
||||
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.event.*;
|
||||
import java.io.*;
|
||||
import java.util.Properties;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A program to test properties. The program remembers the frame position, size,
|
||||
* and last selected file.
|
||||
* @version 1.10 2018-03-15
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ImageViewer
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() -> {
|
||||
var frame = new ImageViewerFrame();
|
||||
frame.setTitle("ImageViewer");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An image viewer that restores position and size from a properties file
|
||||
* and updates the properties upon exit.
|
||||
*/
|
||||
class ImageViewerFrame extends JFrame
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private File propertiesFile;
|
||||
private Properties settings;
|
||||
private String image;
|
||||
private JLabel label = new JLabel();
|
||||
|
||||
public ImageViewerFrame()
|
||||
{
|
||||
// get position, size, title from properties
|
||||
|
||||
String userDir = System.getProperty("user.home");
|
||||
var propertiesDir = new File(userDir, ".corejava");
|
||||
if (!propertiesDir.exists()) propertiesDir.mkdir();
|
||||
propertiesFile = new File(propertiesDir, "ImageViewer.properties");
|
||||
|
||||
var defaultSettings = new Properties();
|
||||
defaultSettings.setProperty("left", "0");
|
||||
defaultSettings.setProperty("top", "0");
|
||||
defaultSettings.setProperty("width", "" + DEFAULT_WIDTH);
|
||||
defaultSettings.setProperty("height", "" + DEFAULT_HEIGHT);
|
||||
defaultSettings.setProperty("title", "");
|
||||
|
||||
settings = new Properties(defaultSettings);
|
||||
|
||||
if (propertiesFile.exists())
|
||||
try (var in = new FileInputStream(propertiesFile))
|
||||
{
|
||||
settings.load(in);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
int left = Integer.parseInt(settings.getProperty("left"));
|
||||
int top = Integer.parseInt(settings.getProperty("top"));
|
||||
int width = Integer.parseInt(settings.getProperty("width"));
|
||||
int height = Integer.parseInt(settings.getProperty("height"));
|
||||
setBounds(left, top, width, height);
|
||||
image = settings.getProperty("image");
|
||||
if (image != null) label.setIcon(new ImageIcon(image));
|
||||
|
||||
addWindowListener(new WindowAdapter()
|
||||
{
|
||||
public void windowClosing(WindowEvent event)
|
||||
{
|
||||
settings.setProperty("left", "" + (int) getX());
|
||||
settings.setProperty("top", "" + (int) getY());
|
||||
settings.setProperty("width", "" + (int) getWidth());
|
||||
settings.setProperty("height", "" + (int) getHeight());
|
||||
if (image != null)
|
||||
settings.setProperty("image", image);
|
||||
try (var out = new FileOutputStream(propertiesFile))
|
||||
{
|
||||
settings.store(out, "Program Properties");
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
ex.printStackTrace();
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
|
||||
// use a label to display the images
|
||||
add(label);
|
||||
|
||||
// set up the file chooser
|
||||
var chooser = new JFileChooser();
|
||||
chooser.setCurrentDirectory(new File("."));
|
||||
|
||||
// set up the menu bar
|
||||
var menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
|
||||
var menu = new JMenu("File");
|
||||
menuBar.add(menu);
|
||||
|
||||
var openItem = new JMenuItem("Open");
|
||||
menu.add(openItem);
|
||||
openItem.addActionListener(event -> {
|
||||
// show file chooser dialog
|
||||
int result = chooser.showOpenDialog(null);
|
||||
|
||||
// if file selected, set it as icon of the label
|
||||
if (result == JFileChooser.APPROVE_OPTION)
|
||||
{
|
||||
image = chooser.getSelectedFile().getPath();
|
||||
label.setIcon(new ImageIcon(image));
|
||||
}
|
||||
});
|
||||
|
||||
var exitItem = new JMenuItem("Exit");
|
||||
menu.add(exitItem);
|
||||
exitItem.addActionListener(event -> System.exit(0));
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package set;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program uses a set to print all unique words in System.in.
|
||||
* @version 1.12 2015-06-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class SetTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var words = new HashSet<String>();
|
||||
long totalTime = 0;
|
||||
|
||||
try (var in = new Scanner(System.in))
|
||||
{
|
||||
while (in.hasNext())
|
||||
{
|
||||
String word = in.next();
|
||||
long callTime = System.currentTimeMillis();
|
||||
words.add(word);
|
||||
callTime = System.currentTimeMillis() - callTime;
|
||||
totalTime += callTime;
|
||||
}
|
||||
}
|
||||
|
||||
Iterator<String> iter = words.iterator();
|
||||
for (int i = 1; i <= 20 && iter.hasNext(); i++)
|
||||
System.out.println(iter.next());
|
||||
System.out.println(". . .");
|
||||
System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package shuffle;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the random shuffle and sort algorithms.
|
||||
* @version 1.12 2018-04-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ShuffleTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
var numbers = new ArrayList<Integer>();
|
||||
for (int i = 1; i <= 49; i++)
|
||||
numbers.add(i);
|
||||
Collections.shuffle(numbers);
|
||||
List<Integer> winningCombination = numbers.subList(0, 6);
|
||||
Collections.sort(winningCombination);
|
||||
System.out.println(winningCombination);
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package sieve;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program runs the Sieve of Erathostenes benchmark. It computes all primes
|
||||
* up to 2,000,000.
|
||||
* @version 1.21 2004-08-03
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Sieve
|
||||
{
|
||||
public static void main(String[] s)
|
||||
{
|
||||
int n = 2000000;
|
||||
long start = System.currentTimeMillis();
|
||||
var bitSet = new BitSet(n + 1);
|
||||
int count = 0;
|
||||
int i;
|
||||
for (i = 2; i <= n; i++)
|
||||
bitSet.set(i);
|
||||
i = 2;
|
||||
while (i * i <= n)
|
||||
{
|
||||
if (bitSet.get(i))
|
||||
{
|
||||
count++;
|
||||
int k = 2 * i;
|
||||
while (k <= n)
|
||||
{
|
||||
bitSet.clear(k);
|
||||
k += i;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
while (i <= n)
|
||||
{
|
||||
if (bitSet.get(i)) count++;
|
||||
i++;
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println(count + " primes");
|
||||
System.out.println((end - start) + " milliseconds");
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
@version 1.21 2004-08-03
|
||||
@author Cay Horstmann
|
||||
*/
|
||||
|
||||
#include <bitset>
|
||||
#include <iostream>
|
||||
#include <ctime>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
const int N = 2000000;
|
||||
clock_t cstart = clock();
|
||||
|
||||
bitset<N + 1> b;
|
||||
int count = 0;
|
||||
int i;
|
||||
for (i = 2; i <= N; i++)
|
||||
b.set(i);
|
||||
i = 2;
|
||||
while (i * i <= N)
|
||||
{
|
||||
if (b.test(i))
|
||||
{
|
||||
count++;
|
||||
int k = 2 * i;
|
||||
while (k <= N)
|
||||
{
|
||||
b.reset(k);
|
||||
k += i;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
while (i <= N)
|
||||
{
|
||||
if (b.test(i))
|
||||
count++;
|
||||
i++;
|
||||
}
|
||||
|
||||
clock_t cend = clock();
|
||||
double millis = 1000.0 * (cend - cstart) / CLOCKS_PER_SEC;
|
||||
|
||||
cout << count << " primes\n" << millis << " milliseconds\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||