- public class sort {
-
-
-
- public static void main(String[] args) {
- int[] data = {8,4,9,2,1,6,3,7,5};
- for (int i = 0; i < data.length; i++) {
- System.out.print(data[i]+" ");
- }
- System.out.println();
- sort s = new sort();
-
- s.sort5(data,0,data.length-1);
- for (int i = 0; i < data.length; i++) {
- System.out.print(data[i]+" ");
- }
- }
-
-
-
-
-
- public void sort1(int[] data){
- for (int i = 0; i < data.length -1; i++) {
- for (int j = 0; j < data.length - i - 1; j++) {
- if (data[j] > data[j + 1]) {
- int temp = data[j];
- data[j] = data[j + 1];
- data[j + 1] = temp;
- }
- }
- }
- }
-
-
-
-
- public void sort2(int data[]) {
- int minVal;
- int minIndex;
- for (int i = 0; i < data.length - 1; i++) {
- minVal = data[i];
- minIndex = i;
-
- for (int j = i + 1; j < data.length; j++) {
- if (data[j] < minVal) {
- minVal = data[j];
- minIndex = j;
- }
- }
-
- if (minVal != data[i] && minIndex != i) {
- data[minIndex] = data[i];
- data[i] = minVal;
- }
- }
-
- }
-
-
-
-
-
- public void sort3(int data[]) {
- for (int i = 1; i < data.length; i++) {
- for (int j = i; j > 0; j--) {
- if (data[j] < data[j - 1]) {
- int temp = data[j];
- data[j] = data[j - 1];
- data[j - 1] = temp;
- }
- }
- }
- }
-
-
-
-
-
-
-
-
-
-
- public void sort4(int data[], int start, int end) {
- if (start < end) {
- int mid = (start + end) / 2;
- sort4(data, start, mid);
- sort4(data, mid + 1, end);
- merge(data, start, mid, end);
- }
- }
-
- public static void merge(int data[], int start, int mid, int end) {
- int temp[] = new int[end - start + 1];
- int i = start;
- int j = mid + 1;
- int k = 0;
- while (i <= mid && j <= end) {
- if (data[i] < data[j]) {
- temp[k++] = data[i++];
- } else {
- temp[k++] = data[j++];
- }
- }
-
- while (i <= mid) {
- temp[k++] = data[i++];
- }
- while (j <= end) {
- temp[k++] = data[j++];
- }
-
- for (k = 0, i = start; k < temp.length; k++, i++) {
- data[i] = temp[k];
- }
- }
-
-
-
-
-
-
- public void sort5(int data[], int start, int end) {
- if (end - start <= 0) {
- return;
- }
- int last = start;
- for (int i = start + 1; i <= end; i++) {
- if (data[i] < data[start]) {
- int temp = data[++last];
- data[last] = data[i];
- data[i] = temp;
- }
- }
- int temp = data[last];
- data[last] = data[start];
- data[start] = temp;
- sort5(data, start, last - 1);
- sort5(data, last + 1, end);
- }
- }
-
public class SortDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//demo2();
int[] arr = {1,9,344,12,7,8,3,4,65,22};
quicksort(arr, 0, arr.length-1);
for(int i:arr){
System.out.print(i+" ");
}
}
//選擇排序
public static void demo(){
int[] arr = {78,9,2,22,445,90,-9,55};
int temp;
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(int a:arr){
System.out.print(a+" ");
}
}
//冒泡排序
public static void demo2(){
int[] arr = {78,9,2,22,445,90,-9,55};
int temp;
for(int i=1;i<arr.length;i++){
for(int j=0;j<arr.length-i;j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(int a=0;a<arr.length;a++){
System.out.print(arr[a]+" ");
}
}
//插入排序
public static void demo3(){
int [] arr= {99,25,3,899,22,-1};
int temp,i,j;
for(i=1;i<arr.length;i++){
temp= arr[i];
for(j=i;j>0&&arr[j-1]>temp;j--){
arr[j]=arr[j-1];
}
arr[j]=temp;
}
for(int a:arr){
System.out.print(a+" ");
}
}
//快速排序start
public static int parttion(int []arr,int lo,int hi){
int key = arr[lo]; //選取基準點
while(lo<hi){
//從後半部分向前掃描
while(arr[hi]>=key&&hi>lo){
hi--;
}
arr[lo]=arr[hi];
//從前半部分向後掃描
while(arr[lo]<=key&&hi>lo){
lo++;
}
arr[hi]=arr[lo];
}
arr[hi]= key; //最後把基準存入
return hi;
}
public static void quicksort(int []arr,int lo,int hi){
if(lo>=hi){
return;
}
//進行第一輪排序獲取分割點
int index = parttion(arr, lo, hi);
//排序前半部分
quicksort(arr,lo,index -1);
//排序後半部分
quicksort(arr,index+1,hi);
}
//快速排序end
}
-
2、多線程相關
-
package hanwl.demo;
/**
* A線程打印10次A,B線程打印10次B,C線程打印10次C,要求線程同時運行,交替打印10次ABC
*/
public class MyThreadPrinter implements Runnable {
private String name;
private Object prev;
private Object self;
public MyThreadPrinter(String name, Object prev, Object self) {
//super();
this.name = name;
this.prev = prev;
this.self = self;
}
@Override
public void run() {
// TODO Auto-generated method stub
int count = 10;
while(count>0){
synchronized(prev){
synchronized(self){
System.out.print(name);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
Object a = new Object();
Object b = new Object();
Object c = new Object();
MyThreadPrinter pa = new MyThreadPrinter("A", c, a);
MyThreadPrinter pb = new MyThreadPrinter("B", a, b);
MyThreadPrinter pc = new MyThreadPrinter("C", b, c);
new Thread(pa).start();
Thread.sleep(100); //確保按順序A、B、C執行
new Thread(pb).start();
Thread.sleep(100);
new Thread(pc).start();
Thread.sleep(100);
}
}
-
package hanwl.demo;
/**
*死鎖例子
*/
public class DeadLock {
public static String obj1 = "obj1";
public static String obj2 = "obj2";
public static void main(String[] args){
Thread a = new Thread(new Lock1());
Thread b = new Thread(new Lock2());
a.start();
b.start();
}
}
class Lock1 implements Runnable{
@Override
public void run(){
try{
System.out.println("Lock1 running");
while(true){
synchronized(DeadLock.obj1){
System.out.println("Lock1 lock obj1");
Thread.sleep(3000);//獲取obj1後先等一下子,讓Lock2有足夠的時間鎖住obj2
synchronized(DeadLock.obj2){
System.out.println("Lock1 lock obj2");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class Lock2 implements Runnable{
@Override
public void run(){
try{
System.out.println("Lock2 running");
while(true){
synchronized(DeadLock.obj2){
System.out.println("Lock2 lock obj2");
Thread.sleep(3000);
synchronized(DeadLock.obj1){
System.out.println("Lock2 lock obj1");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
-
3、IO相關
-
package hanwl.demo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
public class SelectDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//demo();
test2();
}
//給定一個txt文件,如何獲得某字符串出現的次數
public static void demo(){
try {
File file = new File("E://demo.txt");
InputStream is = new FileInputStream(file);
byte b[] = new byte[1024];
int a = is.read(b);
String str[] = new String(b,0,a).split("");
int count = 0;
for(int i = 0;i<str.length;i++){
if("x".equals(str[i])){
count++;
}
}
System.out.println(count);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void test(){
try {
FileReader ins = new FileReader("e:\\demo.txt");
char [] buf = new char[6];
int num = 0;
while((num = ins.read(buf))!=-1){
System.out.print(new String(buf,0,num));
}
ins.close();
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
//讀取磁盤文件到控制檯
public static void test2(){
try {
FileReader ins = new FileReader("e:\\demo.txt");
BufferedReader br = new BufferedReader(ins);
char [] buf = new char[6];
int num = 0;
while((num = br.read(buf))!=-1){
System.out.print(new String(buf,0,num));
}
br.close();
ins.close();
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
}
-
4、單例模式
-
package hanwl.singleton;
//單例模式
//用「雙重檢查加鎖」,在getInstance()中減小使用同步
public class Singleton3 {
private volatile static Singleton3 instance;
private Singleton3(){}
public static Singleton3 getInstance(){
if(instance==null){
synchronized (Singleton3.class) {
if(instance==null){
instance =new Singleton3();
}
}
}
return instance;
}
}
-
package hanwl.singleton;
/**
* 單例模式
* 懶漢式
* 線程安全給get方法增長
*/
public class Singleton2 {
private static Singleton2 instance;
private Singleton2(){}
public static synchronized Singleton2 getInstance(){
if(instance==null){
instance = new Singleton2();
}
return instance;
}
}
-
package hanwl.singleton;
/**
* 單例模式
* 餓漢式
*/
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return instance;
}
}
package hanwl.singleton;
public class MyThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Singleton.getInstance().hashCode());
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread[] mts = new MyThread[10];
for(int i=0;i<mts.length;i++){
mts[i]=new MyThread();
}
for (int j = 0; j < mts.length; j++) {
mts[j].start();
}
}
}
-
5、一些面試題
-
package hanwl.demo;
public class ArrayDemo {
/**
* 有兩個有序數組a[]和b[],將它們合併成數組c[],須要c[]也是有序數組,考慮時間複雜度
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sortArray();
}
public static void sortArray(){
int [] a = {1,5,22,44,98};
int [] b = {2,4,18,33,50,90,109,180,222};
//定義一個新數組,長度爲兩個數組長度之和
int [] c = new int[a.length+b.length];
//i:a數組下標 j:b數組下標 k:新數組下標
int i=0,j=0,k=0;
//按位循環比較兩個數組,較小元素的放入新數組,下標加一(注意,較大元素對應的下標不加一),直到某一個下標等於數組長度時退出循環
while(i<a.length&&j<b.length){
if(a[i]<=b[j]){
c[k++]=a[i++];
}else{
c[k++]=b[j++];
}
}
/* 後面連個while循環是用來保證兩個數組比較完以後剩下的一個數組裏的元素能順利傳入 *
* 此時較短數組已經所有放入新數組,較長數組還有部分剩餘,最後將剩下的部分元素放入新數組,大功告成*/
while(i<a.length){
c[k++]=a[i++];
}
while(j<b.length){
c[k++]=b[j++];
}
for(int x=0;x<c.length;x++){
System.out.print(c[x]+",");
}
}
}
-
package hanwl.string;
public class StringDemo {
/**
* 字符串反轉
* @param args
*/
public static void main(String[] args) {
//String str = "aaabbbcccddd";
//reversell(str);
reverseDemo();
//demo();
}
public static String reversell(String str){
return new StringBuffer(str).reverse().toString();
}
public static void reverseDemo(){
String str = "aaabbbcccddd";
StringBuffer sb = new StringBuffer();
for(int i=str.length()-1;i>=0;i--){
char ch = str.charAt(i);
sb.append(ch);
}
System.out.println(sb.toString());
}
public static void demo(){
int count = 0;
int num = 0;
for(int i=0;i<=100;i++){
num = num+i;
count = count++;
}
System.out.println(num*count);
}
}
-
package hanwl.demo;
import java.io.File;
public class ListFileDemo {
/**
* 遞歸列出某個路徑下的全部文件名,包括子目錄
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("e:\\資料文件");
listFile2(file);
}
public static void listFile(File file){
File [] subFile = file.listFiles();
for(File f:subFile){
if(f.isDirectory()){
listFile(f);
}
else{
System.out.println(f);
}
//System.out.println(f.getName());
}
}
public static void listFile2(File file){
File [] subFile = file.listFiles();
for(int i=0;i<subFile.length;i++){
if(subFile[i].isDirectory()){
listFile2(subFile[i]);
}
else{
System.out.println(subFile[i].getAbsolutePath());
}
}
}
}
-
import java.io.File;
/**
* 遞歸列出某個路徑下的全部文件名,包括子目錄,帶級別
* @author loong
*
*/
public class ListFileDemo3 {
public static void main(String[] args)
{
File dir = new File("e:\\KanKan");
showDir(dir,0);
//System.out.println(dir.delete());
}
public static String getLevel(int level)
{
StringBuilder sb = new StringBuilder();
sb.append("|--");
for(int x=0; x<level; x++)
{
//sb.append("|--");
sb.insert(0,"| ");
}
return sb.toString();
}
public static void showDir(File dir,int level)
{
System.out.println(getLevel(level)+dir.getName());
level++;
File[] files = dir.listFiles();
for(int x=0; x<files.length; x++)
{
if(files[x].isDirectory())
showDir(files[x],level);
else
System.out.println(getLevel(level)+files[x]);
}
}
}
-
6、JDBC例子
-
package hanwl.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//加載數據庫驅動
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
String url = "jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF8";
String username = "root";
String password = "root";
//獲取數據庫鏈接(就是用Java鏈接數據庫)對象
Connection conn = DriverManager.getConnection(url, username, password);
//操做數據庫
//1.建立Statement對象,用於操做數據庫
//2.利用Statement對象的相關方法,操做數據庫
//3.若是執行查詢語句,需建立ResultSet對象,此對象爲查詢結果集
Statement stmt = conn.createStatement();
//查詢部門信息包括部門的平均工資
String sql = "select dept.did id,dname name,avg(emp.salary) pjgz from emp,dept where emp.did = dept.did group by dept.did,dname;";
//查詢部門平均工資小於3500的部門信息
String sql2 ="select b.* ,avg(a.salary) from emp a,dept b where a.did=b.did and b.did in (select did from emp group by did having avg(salary)<3500) group by b.did;";
//查詢工資低於部門平均工資的員工信息
String sql3 ="select a.ename, a.salary from emp a where salary<(select avg(salary)from emp where a.did=did group by did);";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt("id")+" ");
System.out.print(rs.getString("name")+" ");
System.out.println(rs.getString("pjgz"));
}
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
-
/**
* 一個整形數組,數組裏有正數也有負數。 數組中連續的一個或多個整數組成一個子數組,
* 每一個子數組都有一個和,求全部子數組的和的最大值,要求時間複雜度爲O(n)
* @author
*/
public class Test {
public static void main(String[] args) {
int[] a = { 1, -2, 3, 10, -4, 7, 2, -5 };
int max = MaxSum(a);
System.out.println(max);
}
/*** * @param a 源數組 * @return 返回子數組和的最大值 */
public static int MaxSum(int[] a) {
int sum = 0;
int max = 0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[a.length - i - 1];
if (a[a.length - i - 1] >= 0) {
if (max < sum) {
max = sum;
}
}
if (sum < 0) {
sum = 0;
}
}
return max;
}
}
-
/*
二分查找法。
*/
public static int halfSearch(int[] arr,int key)
{
int max,min,mid;
min = 0;
max = arr.length-1;
mid = (max+min)/2;
while(arr[mid]!=key)
{
if(key>arr[mid])
min = mid + 1;
else if(key<arr[mid])
max = mid - 1;
if(max<min)
return -1;
mid = (max+min)/2;
}
return mid;
}
-
/*
* 練習:
* "fdgavcbsacdfs" 獲取該字符串中,每個字母出現的次數。
* 要求打印結果是:a(2)b(1)...;
* 思路:
* 對於結果的分析發現,字母和次數之間存在着映射的關係。並且這種關係不少。
* 不少就須要存儲,能存儲映射關係的容器有數組和Map集合。
* 關係一方式有序編號嗎?沒有!
* 那就是使用Map集合。 又發現能夠保證惟一性的一方具有着順序如 a b c ...
* 因此可使用TreeMap集合。
*
* 這個集合最終應該存儲的是字母和次數的對應關係。
*
* 1,由於操做的是字符串中的字母,因此先將字符串變成字符數組。
* 2,遍歷字符數組,用每個字母做爲鍵去查Map集合這個表。
* 若是該字母鍵不存在,就將該字母做爲鍵 1做爲值存儲到map集合中。
* 若是該字母鍵存在,就將該字母鍵對應值取出並+1,在將該字母和+1後的值存儲到map集合中,
* 鍵相同值會覆蓋。這樣就記錄住了該字母的次數.
* 3,遍歷結束,map集合就記錄全部字母的出現的次數。oy.
*
*
*/
public class MapTest {
/**
* @param args
*/
public static void main(String[] args) {
String str = "fdg+avAdc bs5dDa9c-dfs";
String s = getCharCount(str);
System.out.println(s);
}
public static String getCharCount(String str) {
//將字符串變成字符數組
char[] chs = str.toCharArray();
//定義map集合表。
Map<Character,Integer> map = new TreeMap<Character,Integer>();
for (int i = 0; i < chs.length; i++) {
if(!(chs[i]>='a' && chs[i]<='z' || chs[i]>='A' && chs[i]<='Z'))
// if(!(Character.toLowerCase(chs[i])>='a' && Character.toLowerCase(chs[i])<='z'))
continue;
//將數組中的字母做爲鍵去查map表。
Integer value = map.get(chs[i]);
int count = 1;
//判斷值是否爲null.
if(value!=null){
count = value+1;
}
// count++;
map.put(chs[i], count);
/*
if(value==null){
map.put(chs[i], 1);
}else{
map.put(chs[i], value+1);
}
*/
}
return mapToString(map);
}
private static String mapToString(Map<Character, Integer> map) {
StringBuilder sb = new StringBuilder();
Iterator<Character> it = map.keySet().iterator();
while(it.hasNext()){
Character key = it.next();
Integer value = map.get(key);
sb.append(key+"("+value+")");
}
return sb.toString();
}
}
-
遍歷map的4種方式的比較
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
//第一種:廣泛使用,二次取值
System.out.println("經過Map.keySet遍歷key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二種
System.out.println("經過Map.entrySet使用iterator遍歷key和value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第三種:推薦,尤爲是容量大時
System.out.println("經過Map.entrySet遍歷key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四種 System.out.println("經過Map.values()遍歷全部的value,但不能遍歷key"); for (String v : map.values()) { System.out.println("value= " + v); } }