public static void main(String[] args) {
var list = new ArrayList<String>();
list.add("hello,world!");
System.out.println(list);
}
这是最平常的使用。注意赋值语句右边,最好写上泛型类型,否则会有如下情况:
public static void main(String[] args) {
var list = new ArrayList<>();
list.add("hello,world!");
list.add(1);
list.add(1.01);
System.out.println(list);
}
public static void main(String[] args) {
var list = new ArrayList<String>();
list.add("hello,world!");
System.out.println(list);
list = new ArrayList<Integer>(); //编译报错
}
!!!:下面几点使用限制
局部变量初始化
for循环内部索引变量
传统的for循环声明变量
方法参数
全局变量
构造函数参数
方法返回类型
字段
捕获表达式(或任何其他类型的变量声明)
public static void main(String[] args) {
//局部变量初始化
var list = new ArrayList<String>();
//for循环内部索引变量
for (var s : list) {
System.out.println(s);
}
//传统的for循环声明变量
for (var i = 0; i < list.size(); i++) {
System.out.println(i);
}
}
public static var list = new ArrayList<String>(); //编译报错
public static List<String> list = new ArrayList<>(); //正常编译通过
public interface MyInterface {
void normalInterfaceMethod();
default void interfaceMethodWithDefault() {
init();
}
default void anotherDefaultMethod() {
init();
}
// This method is not part of the public API exposed by MyInterface
private void init() {
System.out.println("Initializing");
}
}
publicclassBlock{public String hash;public String previousHash;private String data;//our data will be a simple message.private long timeStamp;//as number of milliseconds since 1/1/1970.//Block Constructor. publicBlock(String data,String previousHash ){this.data = data;this.previousHash = previousHash;this.timeStamp =newDate().getTime();}}
import java.security.MessageDigest;//通过导入MessageDigest来使用SHA256publicclassStringUtil{//Applies Sha256 to a string and returns the result. publicstatic String applySha256(String input){try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");//Applies sha256 to our input,
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuffer hexString =newStringBuffer();// This will contain hash as hexidecimalfor(int i =0; i < hash.length; i++){
String hex = Integer.toHexString(0xff& hash[i]);if(hex.length()==1) hexString.append('0');
hexString.append(hex);}return hexString.toString();}catch(Exception e){thrownewRuntimeException(e);}}//Short hand helper to turn Object into a json stringpublicstatic String getJson(Object o){returnnewGsonBuilder().setPrettyPrinting().create().toJson(o);}//Returns difficulty string target, to compare to hash. eg difficulty of 5 will return "00000" publicstatic String getDificultyString(int difficulty){returnnewString(newchar[difficulty]).replace('\0','0');}}
好,现在我们在Block里添加生成hash的方法:
//Calculate new hash based on blocks contentspublic String calculateHash(){
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp)+
Integer.toString(nonce)+
data
);return calculatedhash;}
然后我们在构造函数里添加hash值的计算:
//Block Constructor. publicBlock(String data,String previousHash ){this.data = data;this.previousHash = previousHash;this.timeStamp =newDate().getTime();this.hash =calculateHash();//Making sure we do this after we set the other values.}
一试身手
现在是时候一试身手了。我们新建一个main类来玩耍一次:
publicstaticvoidmain(String[] args){
Block genesisBlock =newBlock("Hi im the first block","0");
System.out.println("block 1的hash值 : "+ genesisBlock.hash);
Block secondBlock =newBlock("Yo im the second block",genesisBlock.hash);
System.out.println("block 2的hash值: "+ secondBlock.hash);
Block thirdBlock =newBlock("Hey im the third block",secondBlock.hash);
System.out.println("block 3的hash值: "+ thirdBlock.hash);}
publicstatic ArrayList<Block> blockchain =newArrayList<Block>();publicstaticvoidmain(String[] args){//add our blocks to the blockchain ArrayList:
blockchain.add(newBlock("Hi im the first block","0"));
blockchain.add(newBlock("Yo im the second block",blockchain.get(blockchain.size()-1).hash));
blockchain.add(newBlock("Hey im the third block",blockchain.get(blockchain.size()-1).hash));
String blockchainJson =newGsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println(blockchainJson);}
publicstatic Boolean isChainValid(){
Block currentBlock;
Block previousBlock;
String hashTarget =newString(newchar[difficulty]).replace('\0','0');//循环遍历每个块检查hashfor(int i=1; i < blockchain.size(); i++){
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i-1);//比较注册的hash和计算的hash:if(!currentBlock.hash.equals(currentBlock.calculateHash())){
System.out.println("Current Hashes not equal");returnfalse;}//比较上一个块的hash和注册的上一个hash(也就是previousHash)if(!previousBlock.hash.equals(currentBlock.previousHash)){
System.out.println("Previous Hashes not equal");returnfalse;}//检查hash是否被处理if(!currentBlock.hash.substring(0, difficulty).equals(hashTarget)){
System.out.println("This block hasn't been mined");returnfalse;}}returntrue;}
对区块链中的块的任何更改都将导致此方法返回false。
On the bitcoin network nodes share their blockchains and the longest valid chain is accepted by the network. What’s to stop someone tampering with data in an old block then creating a whole new longer blockchain and presenting that to the network ? Proof of work. The hashcash proof of work system means it takes considerable time and computational power to create new blocks. Hence the attacker would need more computational power than the rest of the peers combined.
publicclassImportChain{publicstatic ArrayList<Block> blockchain =newArrayList<Block>();publicstatic int difficulty =5;publicstaticvoidmain(String[] args){//add our blocks to the blockchain ArrayList:
System.out.println("正在尝试挖掘block 1... ");addBlock(newBlock("Hi im the first block","0"));
System.out.println("正在尝试挖掘block 2... ");addBlock(newBlock("Yo im the second block",blockchain.get(blockchain.size()-1).hash));
System.out.println("正在尝试挖掘block 3... ");addBlock(newBlock("Hey im the third block",blockchain.get(blockchain.size()-1).hash));
System.out.println("\nBlockchain is Valid: "+isChainValid());
String blockchainJson = StringUtil.getJson(blockchain);
System.out.println("\nThe block chain: ");
System.out.println(blockchainJson);}publicstatic Boolean isChainValid(){
Block currentBlock;
Block previousBlock;
String hashTarget =newString(newchar[difficulty]).replace('\0','0');//loop through blockchain to check hashes:for(int i=1; i < blockchain.size(); i++){
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i-1);//compare registered hash and calculated hash:if(!currentBlock.hash.equals(currentBlock.calculateHash())){
System.out.println("Current Hashes not equal");returnfalse;}//compare previous hash and registered previous hashif(!previousBlock.hash.equals(currentBlock.previousHash)){
System.out.println("Previous Hashes not equal");returnfalse;}//check if hash is solvedif(!currentBlock.hash.substring(0, difficulty).equals(hashTarget)){
System.out.println("This block hasn't been mined");returnfalse;}}returntrue;}publicstaticvoidaddBlock(Block newBlock){
newBlock.mineBlock(difficulty);
blockchain.add(newBlock);}}
import java.util.Date;publicclassBlock{public String hash;public String previousHash;private String data;//our data will be a simple message.private long timeStamp;//as number of milliseconds since 1/1/1970.private int nonce;//Block Constructor. publicBlock(String data,String previousHash ){this.data = data;this.previousHash = previousHash;this.timeStamp =newDate().getTime();this.hash =calculateHash();//Making sure we do this after we set the other values.}//Calculate new hash based on blocks contentspublic String calculateHash(){
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp)+
Integer.toString(nonce)+
data
);return calculatedhash;}//Increases nonce value until hash target is reached.publicvoidmineBlock(int difficulty){
String target = StringUtil.getDificultyString(difficulty);//Create a string with difficulty * "0" while(!hash.substring(0, difficulty).equals(target)){
nonce ++;
hash =calculateHash();}
System.out.println("Block已挖到!!! : "+ hash);}}
Method[] methods = classz.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(method)) {
System.out.println(“——befor——:You can do something in here.”);
methods[i].invoke(obj, args);
System.out.println(“——after——:You can do something in here too.”);
近期评论