- 数据结构二叉树的代码实现
package cn.dujiang.demo;
import java.util.Arrays;
class Book implements Comparable<Book>{ //实现比较
private String title ;
private double price ;
public Book(String title,double price){
this.title = title ;
this.price = price ;
}
@Override
public String toString() {
return "书名:"+this.title +",价格:"+ this.price + "\n";
}
@Override
public int compareTo(Book o) { //Arrays.sort()会自动调用方法比较
if (this.price > o.price) {
return 1 ;
} else if (this.price < o.price) {
return -1 ;
}else {
return 0 ;
}
}
}
@SuppressWarnings("rawtypes")
class BinaryTree{
private class Node{
private Comparable data ; //排序依据的是Comparable
private Node left ;//左子树
private Node right ;
@SuppressWarnings("unused")
public Node(Comparable data){
this.data = data ;
}
public void addNode(Node newNode) {
if (this.data.compareTo(newNode.data) < 0 ) {
if (this.left == null) {
this.left = newNode ;
}else {
this.left.addNode(newNode);
}
}else{
if (this.right == null) {
this.right = newNode;
}else{
this.right.addNode(newNode);
}
}
}
public void toArrayNode() {
if(this.left != null){ //表示有左节点
this.left.toArrayNode();
}
BinaryTree.this.retDate[BinaryTree.this.foot ++] = this.data ;
if (this.right != null) {
this.right.toArrayNode(); //右子树输出
}
}
}
private Node root ; //定义根节点
private int count ; //保存元素个数
private Object[] retDate ;
private int foot ;
public void add(Object obj){ //进行数据的追加
Comparable com = (Comparable) obj ; //必须变为Comparable才可以实现Node的保存
Node newNode = new Node(com) ; //创建新的节点
if (this.root == null) { //现在不存在根节点
this.root = newNode ; //保存根节点
}else{
this.root.addNode(newNode) ; //交给Node类处理
}
this.count ++ ;
}
public Object[] toArray(){
if(this.root == null){
return null ;
}
this.foot = 0 ;
this.retDate = new Object[this.count] ;
this.root.toArrayNode() ;
return this.retDate ;
}
}
public class TestDemo {
public static void main(String[] args){
BinaryTree bt = new BinaryTree() ;
bt.add(new Book("Java开发",79.2));
bt.add(new Book("Ja开发",77.2));
bt.add(new Book("Jav开发",76.2));
bt.add(new Book("ava开发",75.2));
Object obj[] = bt.toArray();
System.out.println(Arrays.toString(obj));
}
}
- 正则表达式引出
package cn.dujiang.demo;
/**
* 判断一个字符串是否是字母,是一个很容易的过程
* 但是这样一个简短的操作,却写了八行代码如果有
* 更加复杂的操作的话呢?
* @author Dujiang
*
*/
public class TestDemo {
public static void main(String[] args) throws Exception {
String str = "123";
System.out.println(isNumber(str));
}
public static boolean isNumber(String temp) {
char data[] = temp.toCharArray();// 将字符串变为字符数据,目的是循环取出
for (int x = 0; x < data.length; x++) {
if (data[x] > '9' || data[x] < '0') {
return false;
}
}
return true;
}
}
- 正则简化代码量:
package cn.dujiang.demo;
/**
* "\\d+"就是正则表达式
* @author Dujiang
*
*/
public class TestDemo {
public static void main(String[] args) throws Exception {
String str = "123";
System.out.println(str.matches("\\d+"));
}
}
℃江