import java.util.*;
public class teachermap{
public static void main(String[] args){
//Set text in a string
String text = "Good morning.Having a good class.";
//Creat a TreeMap to hold words as key and count as value
TreeMap map = new TreeMap ();
String[] words = text.split("[ \n\t\r.,;:!?(){}]");
for(int i=0;iif(words[i].length()>1){
if(map.get(key)==null) map.put(key,1);
else{
int value = map.get(key).intValue();
value++;
map.put(key,value);
}
}
}
//Get all entries into a set
Set > entrySet = map.entrySet();
//Get key and value from the each entry
for(Map.Entry entry:entrySet)
System.out.println(entry.getValue()+"\t"+entry.getKey());
}
}
import java.util.concurrent.*;
public class ExecutorDemo {
public static void main(String[] args) {
// Create a fixed thread pool with maximum three threads执行器创建三个线程来并发执行三个
ExecutorService executor = Executors.newFixedThreadPool(3);
// Submit runnable tasks to the executor
executor.execute(new PrintChar('a', 100));
executor.execute(new PrintChar('b', 100));
executor.execute(new PrintNum(100));
// Shut down the executor
executor.shutdown();
}
}
如果将第5行改成 ExecutorService executor = Executors.newFixedThreadPool(1);
这三个任务将顺次执行,因为在线程池中只有一个线程。
如果改成ExecutorService executor = Executors.newFixedThreadPool();
为每个等待的人物任务创建一个新的线程,所以,所有的任务都并发地执行。
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class AccountWithSyncUsingLock {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
// Create and launch 100 threads
for (int i = 0; i < 100; i++) {
executor.execute(new AddAPennyTask());
}
executor.shutdown();
// Wait until all tasks are finished
while (!executor.isTerminated()) {
}
System.out.println("What is balance ? " + account.getBalance());
}
// A thread for adding a penny to the account
public static class AddAPennyTask implements Runnable {
public void run() {
account.deposit(1);
}
}
// An inner class for account
public static class Account {
private static Lock lock = new ReentrantLock(); // Create a lock
private int balance = 0;
public int getBalance() {
return balance;
}
public void deposit(int amount) {
lock.lock(); // Acquire the lock
try {
int newBalance = balance + amount;
// This delay is deliberately added to magnify the
// data-corruption problem and make it easy to see.
Thread.sleep(5);
balance = newBalance;
}
catch (InterruptedException ex) {
}
finally {
lock.unlock(); // Release the lock
}
}
}
}
import java.util.*;
import java.io.*;
public class SerializeDate{
Date d;
SerializeDate(){
d = new Date();
try{
FileOutputStream f = new FileOutputStream("date.ser");
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(d);
f.close();
}
catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]){
SerializeDate b = new SerializeDate();
System.out.println("The saved date is:"+b.d.toString());
}
}
import java.util.*;
import java.io.*;
public class UnSerializeDate{
Date d =null;
UnSerializeDate(){
try{
FileInputStream f = new FileInputStream("date.ser");
ObjectInputStream s = new ObjectInputStream(f);
d = (Date)s.readObject();
f.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
UnSerializeDate a = new UnSerializeDate();
System.out.println("The date read is :"+a.d.toString());
}
}
public class TwoDimArr{
public static void main(String args[]){
int i,j,sum=0;
int[][] ssa={{20,25,26,22},{23,24,20,28}}; //声明数组并设置初值
for(i=0;i//ssa.length表示二维数组的行数
for(j=0;j//ssa[i].length表示第i行的列数
System.out.print("ssa["+i+"]["+j+"]="+ssa[i][j]+" ");
System.out.println();
}
}
}
message = "Welcome";
message.length();//返回7
public class TestFileClass{
public static void main(String[] args){
java.io.File file = new java.io.File("image/us.gif");
System.out.println("Does it exist?"+file.exists());
System.out.println("The file has"+file.length()+"bytes");
System.out.println("Can it be read?"+file.canRead());
System.out.println("Can it be written?"+file.canWrite());
System.out.println("Is it a directory?"+file.isDirectory());
System.out.println("Is it a file?"+file.isFile());
System.out.println("Is it absolute"+file.isAbsolute());
System.out.println("Is it hidden?"+file.isHidden());
}
}
单一职责原则(SRP):一个类尽量只做一件事
开放-封闭原则(OCP):对扩展开放,对修改关闭
依赖倒置原则(DIP):抽象不依赖于具体,具体依赖于抽象
接口隔离原则(ISP):为每个类都单独设计专门的操作接口
Liskov替换原则(LSP):子类型必须能够替换父类型
合成/聚合重用原则(CARP):如果只是达到代码复用的目的,尽量使用组合与聚合,而不是继承
迪米特法则(LoD):封装,类之间的直接联系尽量的少
1.加载:JVM用一个称为类加载器的程序将class的字节码加载到内存中
2.链接:
(1)检查:检查载入的class文件数据的正确性;
(2)准备:为类的静态变量分配存储空间;
(3)解析:将符号引用转换成直接引用
3.初始化:初始化静态变量,静态代码块。
import java.sql.*;
public class SimpleJDBC{
public static void main(String[] args)
throws SQLException,ClassNotFoundException{
//Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
//Establish a connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test");
System.out.println("Database connected");
//Create a statement
Statement statement = connection.createStatement();
//Execute a statement
ResultSet resultSet = statement.executeQuery("select firstName,mi,lastName from Student where lastName = 'Smith'");
//Iterate through the result and print the student names
while(resultSet.next())
System.out.println(resultSet.getString(1)+"\t"+resultSet.getString(2)+"\t"+resultSet.getString(3));
//Close the connection
connection.close();
}
}
多线程可以使程序反应更快,交互性更强,执行效率更高。很多情况下需要使用多线程,如动画和客户机/服务器架构。
由于CPU大部分时间处于空闲状态,例如,CPU在用户输入数据时什么也不做,所以多线程在单处理器系统中共享CPU时间是可行的。
监听器对象必须由源对象注册,注册方法依赖于事件的类型,例如button.AddActionListener(this)
要实现一个监听器接口,就在监听器对象中实现XListener并实现所有处理器方法。
在界面设计中,一个容器是要添加若干组件的,为组件安排在容器中的位置需要使用布局管理器。
框架的默认布局管理器是BorderLayout。
想框架里添加组件,需要在框架里先添加面板
frame.getContentPane().add(label);
使用java开发任何数据库应用程序都需要4个主要借口:Driver Connection Statement 和ResultSet ;
JDBC API定义这些接口,JDBC驱动程序开发商为这些接口提供实现,程序员使用这些借口;
JDBC应用程序使用Driver接口装载一个合适的驱动程序,使用Connection接口连接到数据库,使用Statement接口创建和执行SQL语句,如果语句返回结果的话,使用ResultSet接口处理结果。有一些语句不返回结果,比如SQL数据定义语句和SQL数据修改语句。
import javax.swing.*;// 引入Swing 包
import java.awt.*;//引入awt包,布局管理器及事件类等在其中有定义
public class HelloWorldSwing{
public static void main(String[] args)}
JFrame frame = new JFrame(“HelloWorldSwing”);// 创建并设置顶层容器
final JLabel label = new JLabel(“Hello World!”);// 创建与添加Swing组件
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,70);
frame.setVisible(true);// 显示顶层容器,将整个GUI显示出来
//增加事件处理
}
}
Swing组件不能直接添加到顶层容器中,必须添加到一个与顶层容器相关联的内容面板(Content Pane)上。
frame.getCOntentPane().add(new Jlabel(“Hello!”));
JPanel contentPane = new JPanel();
JButton b = new JButton(“确定”);
contentPane.add(b);
… …
frame.setContentPane(contentPane);
frame.add(child); //child组件将被添加到frame的内容面板中
Swing组件从API类使用上可分为三大类:
- 容器类 :字面意思就是用来包含其它组件的一个容器。例如:JFrame、JApplet、JDialog、JPanel
- 组件类:都是JComponent类(抽象类)的子类。例如:JButton、 JTextField, JTextArea, JComboBox, JList, JRadioButton, JMenu
- 辅助类:是描述和绘制容器类和组件类属性和放置的,如图形环境、颜色、字体、大小以及摆放位置等等,例如:Graphics, Color, Font, FontMetrics, Dimension, LayoutManager。
创建用数字填充的数组线性表,并将新元素插入到线性表的指定位置。本例还利用数组线性表创建一个链表,并将链表插入和删除元素。最后,本例分别向前,向后遍历该链表。
import java.util.*;
public class TestArrayAndLinkedList{
public static void main(String[] args){
List arrayList = new ArrayList();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(1);
arrayList.add(4);
arrayList.add(0,10);
arrayList.add(3,30);
System.out.println("A list of integers in the array list:");
System.out.println(arrayList);
LinkedList
import java.util.*;
public class test{
public static void main(String[] args){
LinkedList linkedList = new LinkedList ();
linkedList.add("red");
linkedList.add("green");
linkedList.add("blue");
Collections.sort(linkedList);//static method
System.out.println(linkedList);
System.out.println(Collections.binarySearch(linkedList,"red"));
}
}
public class CastingDemo {
public static void main(String[] args) {
//Create and initialize two objects
Object object1= new Circle(1);
Object object2 = new Rectangle(1,1);
//Display Circle and rectangle
displayObject(object1);
displayObject(object2);
}
/*A method for displaying an object*/
public static void displayObject(Object object) {
if(object instanceof Circle) {
System.out.println("The circle area is "+((Circle)object).getArea());
System.out.println("The circle diameter is "+((Circle)object).getDiameter());
}
else if(object instanceof Rectangle) {
System.out.println("The Rectangle area is "+((Rectangle)object).getArea());
System.out.println("The Rectangle diameter is "+((Rectangle)object).getPerimeter());
}
}
}
public static void main(String[] args){
int[][] a = new int[][] {{100,2,3,},{4,5,6},{17,8,9}};
matrSum(a);
}
private static void matrSum(int[][] a){
int sum1 = 0;
int sum2 = 0;
for(int i=0;ifor(int j=0;jif(i==j) sum1 += a[i][j];
if(j==a.length-i-1) sum2 += a[i][j];
}
System.out.println("矩阵对角线之和分别是:"+sum1+"和"+sum2);
}