java 基础代码

some java code is very important ,so I describe them at there!
/*
this is Single----------------Single------------------------
*/
class Single{
private static Single s = null;//

private Single(){

}

public static Single getSingle(){
if(s == null) s = new Single();
return s;
}
}


class Single2 {
Single2 s = new Single2();
enum Single{s};
}


---------------------------------------------------------------------------------------
//this is javaCodeConventions
/*
 * Classname:MyjavaCodeConventions
 *
 * Version information:0.0
 *
 * Date:2014-2-25
 *
 * Copyright notice
 */


/*
 * 命名规范:命名规范使程序更易读,从而更易于理解。它们也可以提供一些有关标识符功能的信息,
 * 以助于理解代码,例如,不论它是一个常量,包,还是类。
 * 程序规范:使易于理解和维护,使效率高,尽量避免无关代码
 * 包:com.snc.javacode
 * 类/接口:MyClass、MyInterface
 * 方法:myMethod(),run()
 * 变量:短而且易于记忆 int i,j,k ; char c ,d , e;float fvar;
 * 实例变量: int _employeeId;String _name;Customer _customer;
 * 常量:大写与下划线构成 static final int MIN_WIDTH = 4;
 * 若没有足够理由,不要把实例或类变量声明为公有。通常,实例变量无需显式的设置(set)和获取(gotten),通常这作为方法调用的边缘效应 (side effect)而产生。
 * 一个具有公有实例变量的恰当例子,是类仅作为数据结构,没有行为。亦即,若你要使用一个结构(struct)而非一个类(如果java支持结构的话),
 * 那么把类的实例变量声明为公有是合适的。
 * 
 */
package snc;


/**
 * to describle the java code conventions
 * 
 * @version 0
 * @author Firstname:zjm Lastname:zjm
 * 
 *         文档注释描述Java的类、接口、构造器,方法,以及字段(field)
 */


// @注解


/*
 * 该注释应包含任何有关整个类或接口的信息,而这些信息又不适合作为类/接口文档注释。程序编写:缩进(制表符,if缩进8字符),换行规则(行长度<=70)
 * 注释:文档注释,实现注释,注释不应该包括特殊字符,太多的注释显示出代码的低质量
 */


/*
 * 块注释通常用于提供对文件,方法,数据结构和算法的描述。 块注释被置于每个文件的开始处以及每个方法之前。它们也可以被用于其他地方,
 * 比如方法内部。在功能和方法内部的块注释应该和它们所描述的代码具有一样的缩进格式。
 */


/* 如果一个注释不能在一行内写完,就该采用块注释 */


// 用于注释多余的代码块和行尾注释


public class MyjavaCodeConventions {


/*
* 类的(静态)变量 首先是类的公共变量,随后是保护变量,再后是包一级别的变量 (没有访问修饰符,access modifier),最后是私有变量。
* 实例变量 首先是公共级别的,随后是保护级别的,再后是包一级别的(没有访问修饰符), 最后是私有级别的。
* 尽量在声明局部变量的同时初始化。唯一不这么做的理由是变量的初始值依赖于某些先前发生的计算只在代码块的开始处声明变
*/


public static int ivar = 1;
protected boolean bvar = false;
AnotherClass anotherClass = new AnotherClass();
private AnotherClass anoterClass2 = new AnotherClass();
private int b;


/*
* 构造方法
*/


@SuppressWarnings("static-access")
public MyjavaCodeConventions() {
anotherClass = this.anoterClass2;
b = this.ivar;
}


public MyjavaCodeConventions(boolean bvar) {
super();
this.bvar = bvar;
}


/*
* 这些方法应该按功能,而非作用域或访问权限,分组。 一个私有的类方法可以置于两个公有的实例方法之间。其目的是为了更便于阅读和理解代码。
* 断开代码(,后面,操作符前面)
*/





}


class AnotherClass {
}


============================================
test Scanner and Random  System
============================================
   Random r = new Random();
Scanner s = new Scanner(System.in);
int []a = new int[3];
int []b = new int [10];

for(int i = 0;i < a.length;i++) {
a[i] = s.nextInt();
}
Arrays.sort(a);
int s = (int)n1 + (int)(Math.random()*(n2-n1));
   char c = (char)(c1+Math.random()*(c2 - c1 +1));
================================================
some IO util:              ------IPO-------
================================================
//各种流之间的嵌套关系
new DataInputStream(new BufferedInputStream(new SequenceInputStream(new FileInputStream("d:\\1"), f1)));
new DataInputStream(new BufferedInputStream(new FileInputStream("d:\\1")));
new DataInputStream(new FileInputStream("d:\\1"));

new ObjectInputStream(new BufferedInputStream(new FileInputStream("d:\\1")));
new ObjectInputStream(new FileInputStream("d:\\1"));


public class IoUtil {


public static void close(InputStream is) {
if (is != null) {
try {
is.close();// 关闭文 件流
} catch (IOException e) {
// 由于本错添没有处理价值,因此在异常处理代码中不做任何处理
// 最多在日 志中记录一下当前文 件无法关闭
}
}
}


public static void close(OutputStream os) {
if (os != null) {
try {
os.close();// 关闭文 件流
} catch (IOException e) {
// 由于本错添没有处理价值,因此在异常处理代码中不做任何处理
// 最多在日 志中记录一下当前文 件无法关闭
}
}
}


/*读取文件+中的文件,并显示到面板*/
public static void readFile(String catalog,String fileName){


int b = 0;
byte buffer[] = new byte[2500];
try{
File f = new File(catalog,fileName);
FileInputStream file = new FileInputStream(f);
b = file.read(buffer,0,2500);
try{
String str = new String(buffer,0,b,"Default");
System.out.println(str);
}catch(UnsupportedEncodingException u){
System.out.println("the encoding was not found: "+u);
}
}catch(IOException e){
System.out.println("File is read Error");
}

}




/*复制文件*/
public static void copyFile(File sorceFile, File targetFile)
throws IOException {
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
is = new BufferedInputStream(new FileInputStream(sorceFile));
os = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] b = new byte[1024 * 5];
int len;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
os.flush(); // 关闭链接前需要刷新缓冲区
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 通过抽取公共方法形成工具类,简化程序,提高代码重用
IoUtil.close(is);
IoUtil.close(os);


}


}


public static void fileReadWritetofile(File inFile,File outFile) throws IOException{
InputStream is = null;
OutputStream os = null;

try{
is = new BufferedInputStream(new FileInputStream(inFile),4*1024);
    os = new BufferedOutputStream(new FileOutputStream(outFile),4*1024);

    int len = 0;
    byte[]bytes = new byte[4*1024];
    while((len = is.read(bytes))!= -1){
    os.write(bytes,0,len);
    }
    os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(is);
IoUtil.close(os);
}

}




/* 复制文件夹*/
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile = file[i];
// 目标文件
File targetFile = new File(
new File(targetDir).getAbsolutePath() + File.separator
+ file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1 = sourceDir + "/" + file[i].getName();
// 准备复制的目标文件夹
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
/* the object serializable */
// 持久化对象,将对象写入到文 件中
public static void writeObject(Object obj, File file) {
// 写入顺序 obj(Object)->oos(ObjectOutStream)--byte[]->fos(FileOutputStream)->file(File)
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(file); // 支持二进制的文 件写入流
oos = new ObjectOutputStream(fos); // 将对象流和文
// 件流关联起来
oos.writeObject(obj);// 将对象转换为字节流,并写入到文 件中
oos.flush();// 将缓存中内容刷到介质中

} catch (IOException e) {
e.printStackTrace();
}finally{
// 通过抽取公共方法形成工具类,简化程序,提高代码重用

IoUtil.close(fos);
}
}


// 读取对象,从文 件中恢复对象
public static Object readObject(File file) {
// 流处理过程 file(File)->fis(FileInputStream)->ois(ObjectInputStram)->object(Object)
Object obj = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(file);  //用二进制流读取文 件内容
ois = new ObjectInputStream(fis);  //将二进制流提供给对象流解析
obj = ois.readObject(); //根据文 件内容恢复对象
//ois.close();// 关闭文 件流
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
// 通过抽取公共方法形成工具类,简化程序,提高代码重用

IoUtil.close(ois);
}

return obj;
}




// // 创建序列化对象
// Person person = new Person();
// person.setId(1);
// person.setName("张三");
// person.setPwd("1998998");//pwd 为非序列化元素
// // 对象写入的文 件 new file ——》写入--》恢复对象
// File file = new File("c:/object.serperson");
// IoUtil.writeObject(person, file);
//
// // 从序列化文 件中恢复对象
// Person result = (Person)IoUtil.readObject(file);
// System.out.println("id:\t " + result.getId() + " name: " 
// + result.getName() + " \tpwd: \t" + result.getPwd());
// //id: 1 name: 张三 pwd: null




public static void printDataoutputstreamTofile(String s,File f)throws IOException{
DataOutputStream ds = null;
try{
ds = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
ds.writeUTF(s);
ds.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(ds);
}
}

    public static void printWriter(String s,File f)throws IOException{
PrintWriter p = null;
try{
p = new PrintWriter(f);
p.println(s);

}catch(IOException e){
e.printStackTrace();
}finally{
if (p != null) {
p.close();// 关闭文 件流
}
}
}


public static void testWriter(char[]chars, File f)throws Exception{
FileWriter w = null;
try{
w = new FileWriter(f);
w.write(chars);
w.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
if (w != null) {
try {
w.close();// 关闭文 件流
} catch (IOException e) {
// 由于本错添没有处理价值,因此在异常处理代码中不做任何处理
// 最多在日 志中记录一下当前文 件无法关闭
}
}
}
}

    public static void fileReadWritetofile(File inFile,File outFile) throws IOException{
InputStream is = null;
OutputStream os = null;

try{
is = new BufferedInputStream(new FileInputStream(inFile),4*1024);
    os = new BufferedOutputStream(new FileOutputStream(outFile),4*1024);

    int len = 0;
    byte[]bytes = new byte[4*1024];
    while((len = is.read(bytes))!= -1){
    os.write(bytes,0,len);
    }
    os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
IoUtil.close(is);
IoUtil.close(os);
}

}

public static void writeGBK(){
OutputStreamWriter osw = null;
try{

osw = new OutputStreamWriter( new FileOutputStream("c:\\gbk.txt"),"GBK");
   osw.write("abc");
   osw.write("发布");
   
   osw.flush();

}catch(IOException e){
System.out.println(e);
}finally{
if (osw != null) {
try {
osw.close();// 关闭文 件流
} catch (IOException e) {
// 由于本错添没有处理价值,因此在异常处理代码中不做任何处理
// 最多在日 志中记录一下当前文 件无法关闭
}
}
}
}

public static void readGBK(){
try{
 
BufferedReader reader 
= new BufferedReader(new InputStreamReader(new FileInputStream("C:\\gbk.txt"),"GBK"));
   String s;
   while((s = reader.readLine())!=null){
    System.out.println("read:  "+s);
   }
   reader.close();
}catch(IOException e){
e.printStackTrace();
}
}

public static void readUTF8(){
try{
BufferedReader reader
= new BufferedReader(new InputStreamReader(new FileInputStream("c:\\gbk.txt"),"UTF-8"));
   String s;
   while((s = reader.readLine())!=null){
    System.out.println("read:  "+s);
   }
   reader.close();
}catch(IOException e){
e.printStackTrace();
}
}


}




================================================
Exception  
================================================
try
{
是必须的
}
catch ()

可有多个
}
finally 代码必须得到执行,try与finally最多一个

java.lang.Object
  |
 -|----.Throwable
 -|----.Error
 -|----.Exception
         -|----.IOException
-|----.RuntimeException
           -|----.ArithmeticException
-|----.ArrayIndexOutOfBoundsException
-|----.NumberFormatException



//Account   //存钱 //取款 throws InsufficientFundsException(自定义异常)
public class Account {


private String name;     //取款人姓名
private double balance;  //余额

public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}


public String getName() {
return name;
}

public double getBalance() {
return balance;
}


//存钱
public void deposite(double dAmount) {
        if(dAmount > 0.0)  balance += dAmount;
    }


//取款
public void withdrawal(double dAmount) throws InsufficientFundsException {
if(dAmount > balance) {
String message = "取款金额超过了账户的当前余额";
throw new InsufficientFundsException(message, this, dAmount);
}
balance = balance - dAmount;
}
}




/**
 * 首先自定义异常 类
 * @author Administrator
 *
 */
public class InsufficientFundsException extends Exception {


    private Account  account;      //账号
    private double excepAmount;   //异常 的取款金额

//message参数是传给Exception类的
public InsufficientFundsException(String message, Account account, double  dAmount) {
super(message);
this.account = account;
this.excepAmount = dAmount;
}


public Account getAccount() {
return account;
}


public double getExcepAmount() {
return excepAmount;
}




}


//Client


public class Client {


public static void main(String[] args) {
//初始化一个账号
Account account = new Account("张三", 1000.0);


//存钱
account.deposite(100);
//查询余额
System.out.println("当前余额是: " + account.getBalance());

//取款(处理业务的try)
try{
account.withdrawal(50);
} catch(InsufficientFundsException e) {
e.printStackTrace();  //这是简单的异常 处理方式,直接将错误信息输出到控制台。实际项目中会使用log4j将钷误信息记录到日 志中,以便以后进行统计分析
}
//查询余额
System.out.println("取款50后的当前余额是: " + account.getBalance());

try{
account.withdrawal(10000);
} catch(InsufficientFundsException e) {
e.printStackTrace();  //这是简单的异常 处理方式,直接将错误信息输出到控制台。实际项目中会使用log4j将钷误信息记录到日 志中,以便以后进行统计分析
}
}


}




static int test(){
    int x = 1;
    try{
    return x;
    }
    finally{
    ++x;
    System.out.print("x=");
    //return x; //无返回1,有返回2
    }
    }




==================================================
java集合框架(对外的接口,接口的实现,集合的算法) Collection  Map
==================================================
interface.java.util.Collection
  |
 -|----.List
 -|----.Set
         -|----.SortedSet


interface.java.util.Map
  |
 -|----.SortedMap


------------------------------------------List:ArrayList---------------------------------------------


System.out.println("这是ArrayListd的例子:add(),get(),set(),remove(),和两种遍历方式:");
     String str[] =  {"ab","cd","er","gh","ij"};
     ArrayList list = new ArrayList();
     list.add("litter are: ");
     
     for(int i = 0;i < str.length; i++){
    list.add(str[i]);
     }
     
     list.add(",that's all");
     System.out.println("the arraylist is: ");
     for(int i = 0;i < list.size();i++){
    System.out.print(list.get(i));
     }
     System.out.println();
     //list.remove(1);
     list.set(4,"AB");//设置数组第4个为AB
     Iterator iter = list.iterator();
     while(iter.hasNext()){
    Object temp = iter.next();
    System.out.print(temp);
     }
     System.out.println();
}


---------------------------------------------------------------------------------------




public static void main(String[] args) {
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
list.add("g");


Iterator iter = list.iterator();
while(iter.hasNext()) {
String node = (String)iter.next();
System.out.println(node);
iter.remove();

//遍历集合时不要删除集合中的元素,这样通常 会引发异常
//list.remove(6);
}
}
---------------------------------------------------------------------------------------


public static void main(String[] args) {
List list = new ArrayList();
//基本操作
Person person = new Person();
person.setName("person");
list.add(person);
System.out.println(list.size());
System.out.println(list.isEmpty());

/*
* 与索引下载有关的方法
*/
Person person1 = new Person();
person1.setName("person1");
list.add(0, person1);     //将person1插入到集合的第一个位置

Person person2 = new Person();
person2.setName("person2");
list.set(0, person2);     //将person2替换到集合的第一个位置

System.out.println(list.indexOf(person2));  //确定person2的下标

/*
* 支持下标索引循环和迭代子循环
*/
//遍历  类似于数组使用下标遍历,下标从0开始
for(int i = 0; i < list.size(); i++) {
Person temp = (Person)list.get(i);
System.out.println(temp.getName());
}

//迭代子循环   这是另一种对集合遍历的方式
Iterator iter = list.iterator();
while(iter.hasNext()) {
Person temp = (Person)iter.next();
System.out.println(temp.getName());
}

}






---------------------------------------LinkedList------------------------------------------------
package com.job.collection.collection_map;
/*
 * Collection
 * |_ _ _Set
 * |      |_ _SortedSet
 * |      |     |__TreeSet
 * |      |__HashSet
 * |
 * |_ _ _List
 *        |___ArrayList
 *        |___LinkedList
 *        对集合框架的理解,各个结合间的区别,使用
 */
 public static void main(String[] args) {
//栈实现   先进后出、后进先出
LinkedList stack = new LinkedList();
stack.push("a");   //入栈
stack.push("b");
System.out.println(stack.size());   //栈大小
String temp = (String)stack.pop();   //出栈
System.out.println("temp: " + temp);  //b

//队列实现      先进先出
LinkedList queue = new LinkedList();
queue.addLast("a");   //入队列
queue.addLast("b");
queue.addLast("c");
System.out.println(queue.size());  //队列大小
while(queue.isEmpty()){
String temp1 = (String)queue.poll();   //出队列
System.out.println("temp1: " + temp1);  //a
}
}
-------------------------Collection----------------------------
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


 class Person {


private String name;


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}

}
 
public class TestCollection {



//单 个集合元素的操作
public void single() {
Collection coll = new ArrayList();
Person person = new Person();
System.out.println(coll.add(person)); //增加第一个元素,返回true
System.out.println(coll.size());      //此时集合大小为1
System.out.println(coll.isEmpty());      //判断集合是否为空
System.out.println(coll.contains(person));      //判断集合是否包含指定对象


System.out.println("----------------------------------");      

System.out.println(coll.remove(person)); //删除元素,返回true
System.out.println(coll.size());      //此时集合大小为0
System.out.println(coll.isEmpty());      //判断集合是否为空
System.out.println(coll.contains(person));      //判断集合是否包含指定对象
}

//多个集合地素的操作
public void mutli() {
//构造集合对象
Person person1 = new Person();
person1.setName("person1");
Person person2 = new Person();
person2.setName("person2");
Person person3 = new Person();
person3.setName("person3");
Person person4 = new Person();
person4.setName("person4");
Person person5 = new Person();
person5.setName("person5");
Person person6 = new Person();
person6.setName("person6");
String str = "Hello";

//构造第一个集合
Collection coll = new ArrayList();
coll.add(person1);
coll.add(person2);
coll.add(person3);
//构造第二个集合
Collection coll2 = new ArrayList();
coll2.add(person4);
coll2.add(person5);
coll2.add(person6);
coll2.add(str);

/*
* 集合间操作
*/
coll.addAll(coll2);                   //将第二个集合加入到第一个集合中
System.out.println(coll.size());      //此时集合大小为7
System.out.println(coll.containsAll(coll2));      //判断集合是否包含指定集合中的所有对象


System.out.println("----------------------------------");      

coll.removeAll(coll2);    //删除指定集合中的所有对象
System.out.println(coll.size());     //此时集合大小为3

coll.retainAll(coll2);       //删除coll中所有不被coll2包含的集合元素
System.out.println(coll.size());     //此时集合大小为0

coll.add(person1);
coll.add(person2);
coll.add(person3);
coll.clear();
System.out.println(coll.size());     //此时集合大小为0


System.out.println("----------------------------------");      

/*
* 遍历集合元素   集合中只增加了三个对象
*/
coll.add(person1);
coll.add(person2);
coll.add(person3);


//迭代子遍历
Iterator iter = coll.iterator();     //不需要自已创建迭代器对象,而 是使用方法从集合中获取
while(iter.hasNext()) {    //判断集合中是否还有下一个元素
Person temp = (Person)iter.next();
System.out.println(temp.getName());
}


System.out.println("----------------------------------");      

//将集合转换为数组
Object[] persons = coll.toArray();        //只能转换为Object[]
for(int i = 0; i < persons.length; i++) {
System.out.println(((Person)persons[i]).getName());
}

Person[] persons1 = new Person[coll.size()];   //根据集合大小来构建相同大小的数组
coll.toArray(persons1);                        //将集合元素复制到数组中,这种方式可以使用对象的具体类型
for(int i = 0; i < persons1.length; i++) {
System.out.println(persons1[i].getName());
}
}

public static void main(String[] args) {
TestCollection test = new TestCollection();

test.mutli();
}


}




------------------------------------Set---------------------------------------------------
package com.job.collection.collection_map;


import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/*
 * Set与list:接口,元素顺序,内容(如何判断Set不允许重复),访问方式
 * Set与Map:接口,存放,内容,关系
 */


public class TestSet {


public static void main(String[] args) {
Set set = new HashSet();

// Set中null值只能加入一个
set.add(null);       //null对明只能加入一次
System.out.println(set.size());   //长度为1
set.add(null);       //null对象不能重复加入
System.out.println(set.size());   //长度为1

set.clear();

/*
* 绝大多数Java类的实例都可以依次加入到Set中
*/
GeneralClass general1 = new GeneralClass();
set.add(general1);
GeneralClass general2 = new GeneralClass();
set.add(general2);
GeneralClass general3 = new GeneralClass();
set.add(general3);
System.out.println("GeneralClass类个数:" + set.size());   //长度还是为3,表示每个对象都增加了进来。

//通过迭代子循环
//Set集合是不能通过下标循环的
Iterator iter = set.iterator();
while(iter.hasNext()) {
GeneralClass temp = (GeneralClass)iter.next();
}

set.clear();

/*
* 相同值的String对象也只能加入一次
*/
String str = "Hello";
set.add(str);
System.out.println(set.size());   //长度为1


String str2 = "Hell";
str2 = str2 + "o";
System.out.println(str2);
String str1 = new String("Hello");    //这里创建两个新的对象,它和str并不是指向同一个对象,但是他们所致的hashcolde相同
System.out.println("str和str1的地址比较: " + (str == str1));       //false
System.out.println("str和str1的equals比较: " + (str.equals(str1)));   //true
System.out.println("str和str3的equals比较: " + (str.equals(str2)));   //true
set.add(str1); 
set.add(str2);//str1不会增加到集合中
System.out.println(set.size());   //长度还是为1,表示没有增加

set.clear();

/*
* 实现重写hashCode和equals方法的类,这将改变类重复规则的计算方法
*/
OverrideClass over1 = new OverrideClass();
set.add(over1);
OverrideClass over2 = new OverrideClass();
set.add(over2);
OverrideClass over3 = new OverrideClass();
set.add(over3);
System.out.println("OverrideClass类个数:" + set.size());   //长度还是为3,表示每个对象都增加了进来。

set.clear();

}


}
/**
 * 通常自定义的Java类,一般不会重写hashCode和equals方法
 */
class GeneralClass {
private int id;


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}
}
/**
 * 重写hashCode和equals方法,改变类的对象相等 的规则
 * 实际编 程中一般不会有这个要求
 */
class OverrideClass {
private String name;


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


/*
* 重写Object的hashCode方法,提供了自定义的hashCode定义。
* 如果两个对象的hashCode值不同则认为两个对象是不相同的,可以按照hashCode值确定对象在Set中的位置
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if(name == null) {
return 1;
}
return name.hashCode();
}


/*
* 重写Object的equals方法,提供了自定义的equals定义。
* 如果放入Set集合的两个对象的hashCode值相同,则调用equals方法判断两个对象是否相等 。
* 如果相等 则不会放入到Set中,如果不等 则放入到Set中。
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
OverrideClass over = (OverrideClass)obj;

if(name == null) {
if(over.getName() == null) {
return true;
} else {
return false;
}
}
return this.name.equals(over.getName());
}
}




--------------------------------------TreeSet-------------------------------------------------
package com.job.collection.collection_map;


import java.util.TreeSet;


import java.util.Iterator;




public class TestTreeSet {


public static void main(String[] args) {
TreeSet<SortClass> set = new TreeSet<SortClass>();
set.add(new SortClass("a"));
set.add(new SortClass("c"));
set.add(new SortClass("b"));

//JDK5中对集合循环的新语法
for(SortClass element : set) {
System.out.println(element.getName());
}

//迭代子循环,和上面写法都是遍历操作
Iterator<SortClass> iter = set.iterator();
while(iter.hasNext()) {
SortClass temp = iter.next();
}
}


}
/**
 * TreeSet中只能放入实现Comparable接口的对象
 * 
 * @author Administrator
 *
 */
class SortClass implements Comparable {
private String name;


public SortClass(String name) {
this.name = name;
}


public String getName() {
return name;
}


@Override
public int compareTo(Object obj) {
SortClass sort = (SortClass) obj;
return name.compareTo(sort.getName());   //String类实现了comparable接口
}
}
-------------------------------------HashMap--------------------------------------------------




public static void main(String[] args) {
HashMap map = new HashMap();

//增加
Person person1 = new Person();
person1.setName("王五");
Person person2 = new Person();
person2.setName("张三");
map.put("wang", person1);
map.put("zhang", person2);

//按Key取值
Person person3 = (Person)map.get("zhang");
System.out.println(person3.getName());     //张三


//是否包含某个key值
System.out.println(map.containsKey("wang"));  


//替换   使用相同Key赋值时,后面的赋值将替换前面的赋值
map.put("zhang", person1);         //使用person1替换原来zhang所对应的值
Person person4 = (Person)map.get("zhang");
System.out.println(person4.getName());     //王五

Person person5 = (Person)map.remove("wang");//按Key删除值
System.out.println(person5.getName());          
System.out.println(map.size());      //大小为1

System.out.println(map.size());      //大小为2
System.out.println(map.isEmpty());   //是否为空


//返回Key集合
map.put("wang", person1);


Set keySet = map.keySet();      //得到Key集合
Iterator iter1 = keySet.iterator();
while(iter1.hasNext()) {
String key = (String)iter1.next();  //得到key值
Person temp = (Person)map.get(key);  //返回key对对应的value
System.out.println("key: " + key + " value: " + temp.getName());
}

//返回Value集合
Collection coll = map.values();   
Iterator iter2 = coll.iterator();
while(iter2.hasNext()) {
Person temp = (Person)iter2.next();  //得到Value
System.out.println("value: " + temp.getName());
}

//按条目获取(key、value)
Set entrySet = map.entrySet();
Iterator iter3 = entrySet.iterator();
while(iter3.hasNext()) {
Map.Entry temp = (Map.Entry)iter3.next();  //得到key、Value对
String key = (String)temp.getKey();
Person p = (Person)temp.getValue();
System.out.println("key: " + key + " value: " + p.getName());
}

}




-----------------------------------------Map----------------------------------------------
package com.job.collection.collection_map;
public class StudentScore {


private String project[] = new String[3];
private String name;
private double score[] = new double[3];

public StudentScore(String name ,String project[],double Score[]){
this.name = name;
this.project = project;
this.score = score;
}


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}




public void printpr(String project[]) {
for(int i = 0;i < project.length;i++){
System.out.print("\t"+project[i]+"\t");
}
}
public void printscore(double[] key) {
for(int i = 0;i <key.length;i++){
System.out.print("\t"+key[i]+"\t");
}
}




public String[] getProject() {
return project;
}




public void setProject(String[] project) {
this.project = project;
}

}




package com.job.collection.collection_map;
/*
 * 使用数组名作为键值(如何使用文件名作为键值)
 * 使用泛型不需要强制转换
 */
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;


public class TestStudet {
public static void main(String[] args) {
String Project[] ={"语文","数学","外语"};
double score1[] = {80 ,90 ,95};
double score2[] = {70 ,92 ,88};
double score3[] = {85 ,89 ,85};
StudentScore stu1 = new StudentScore("张三",Project, score1);
StudentScore stu2 = new StudentScore("李四",Project, score2);
StudentScore stu3 = new StudentScore("王五",Project, score3);
Map<double[],StudentScore> stuscoremap = new HashMap<double[],StudentScore>();

//增加
stuscoremap.put(score1,stu1);
stuscoremap.put(score2,stu2);
stuscoremap.put(score3,stu3);


//是否包含某个key值
System.out.println(stuscoremap .containsKey(score1));  //true
Collection<StudentScore> coll = stuscoremap.values();   
Iterator<StudentScore> iter2 = coll.iterator();
Set<double[]> keySet = stuscoremap .keySet();      //得到Key集合
Iterator<double[]> iter1 = keySet.iterator();
System.out.println("姓名:                                                  三科成绩");
while(iter2.hasNext()) {
double[] key = iter1.next();  //得到key值
StudentScore  temp = (StudentScore )iter2.next();  //得到Value
System.out.println( temp.getName() + "\t");
temp.printpr(Project);
System.out.println( );
temp.printscore(key);
System.out.println( );
}
//返回Key集合

//
// while(iter1.hasNext()) {
// String key = (String)iter1.next();  //得到key值
// StudentScore temp = (StudentScore)stuscore .get(key);  //返回key
// }/

}


}


===================================
GeneralClass<T>
===================================


/**
 * 定义一个泛型类,使用<T>表示泛型定义
 * 
 * @author Administrator
 *
 * @param <T>
 */
public class GeneralClass<T> {
private T obj;     //T表示由泛型来确定类型


public T getObj() {//T表示由泛型来确定类型
return obj;
}


public void setObj(T obj) {//T表示由泛型来确定类型
this.obj = obj;
}
}






public class Client {


public static void main(String[] args) {
GeneralClass<String> test = new GeneralClass<String>();
test.setObj("test");

String name = test.getObj();
System.out.println(name);


}


}


---------------------------------------------------------------------------------------


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class Main {


public static void main(String[] args) {
List<Apple> box = new ArrayList<Apple>();

Apple apple = new Apple();
box.add(apple);      //编译正确

// Strawberry berry = new Strawberry();
// box.add(berry);       //编译错误

Apple apple1 = box.get(0);   //不需要显示造型


HashMap<String, Apple> map = new HashMap<String, Apple>(); //表示key为String类型,Value为Apple类型
map.put("b", new Apple());
Apple apple3 = map.get("b");    //不需要显示造型
}


}
class Fruit{

}
class Apple extends Fruit {

}
class Strawberry extends Fruit {

}
---------------------------------------------------------------------------------------
========================================
算法与应用结构
========================================


public class ZhaoQian {


public static void main(String[] args) {
// TODO Auto-generated method stub
    
     double []m = {100,20,10,5,1,0.5,0.1,0.05,0.02,0.01};
     
     Scanner s = new Scanner(System.in);
     double money = s.nextDouble();
     
     money(money,m);
     }


public static void money(double money,double m[]){
double n[] = new double[m.length];
for(int i=0;i<=n.length-1;i++){
n[0] = Math.floor(money/m[0]);
if(money>0){

n[i] =Math.floor(money/m[i]);
}
money -= n[i]*m[i];
if(n[i]!=0)
System.out.println((int)n[i]+"\t张\t"+m[i]);
}
}


}


---------------------------------------------------------------------------------------


import java.util.Scanner;


public class charu {



public static void main(String[] args) {
// TODO Auto-generated method stub
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        
        int a[] ={78,9,5,5};
        int aa[] = new int [a.length+1]; 
        
        int  h1 = aa.length;    
       aa[a.length] = n;
       for(int i = 0; i <a.length ;i++){
      aa[i] = a[i];
       }
       for(int val:aa)
           System.out.print(val+"\t");
       System.out.println();
       
       
       for(int i=h1-1;i>=1;i--){
        if(aa[i]>aa[i-1]){
        int temp = aa[i];
        aa[i] = aa [i-1];
        aa[i-1] = temp;
        }
       }
       for(int val:aa)
           System.out.print(val+"\t");
       System.out.println();
       
       for(int i = 0;i<aa.length/2;i++){
      int temp = aa[i];
      aa[i] = aa[aa.length-1-i];
      aa[aa.length-1-i] = temp;
       }
       for(int val:aa)
           System.out.print(val+"\t");
       System.out.println();
       // System.out.print(aa[4]+"\t");
       for(int i = 0;i<aa.length/2;i++){
       aa[i] = aa[i]^aa[aa.length-1-i];
       aa[aa.length-1-i] = aa[aa.length-1-i]^aa[i]  ;
       aa[i] = aa[i]^aa[aa.length-1-i];
       }
       for(int val:aa)
           System.out.print(val+"\t");
       System.out.println();
}


}


==================================================
java Design Patterns
==================================================
/*
创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、
备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。


1、开闭原则(Open Close Principle)
开闭原则就是说对扩展开放,对修改关闭。在程序需要进行拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。
所以一句话概括就是:为了使程序的扩展性好,易于维护和升级。想要达到这样的效果,我们需要使用接口和抽象类,后
面的具体设计中我们会提到这点。


2、里氏代换原则(Liskov Substitution Principle)
里氏代换原则(Liskov Substitution Principle LSP)面向对象设计的基本原则之一。 里氏代换原则中说,
任何基类可以出现的地方,子类一定可以出现。 LSP是继承复用的基石,只有当衍生类可以替换掉基类,
软件单位的功能不受到影响时,基类才能真正被复用,而衍生类也能够在基类的基础上增加新的行为。
里氏代换原则是对“开-闭”原则的补充。实现“开-闭”原则的关键步骤就是抽象化。而基类与子类的继承关系就是
抽象化的具体实现,所以里氏代换原则是对实现抽象化的具体步骤的规范。


3、依赖倒转原则(Dependence Inversion Principle)
这个是开闭原则的基础,具体内容:真对接口编程,依赖于抽象而不依赖于具体。


4、接口隔离原则(Interface Segregation Principle)
这个原则的意思是:使用多个隔离的接口,比使用单个接口要好。还是一个降低类之间的耦合度的意思,
从这儿我们看出,其实设计模式就是一个软件的设计思想,从大型软件架构出发,为了升级和维护方便。
所以上文中多次出现:降低依赖,降低耦合。


5、迪米特法则(最少知道原则)(Demeter Principle)
为什么叫最少知道原则,就是说:一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。
6、合成复用原则(Composite Reuse Principle)
原则是尽量使用合成/聚合的方式,而不是使用继承。*/
---------------------------------------------------------------------------------------
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jimin_zhou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值