标题:演示Java中的有无static修饰的方法,变量
/**
* 这个【类里面的方法】访这个类中的实例变量,需要创建一个对象才能访问【可以访问private修饰的,因为在一个类中】
* 在static修饰的方法里面, 不能出现this,
* 所以访问非static修饰的方法,实例变量,需要创建一个对象,才能访问
* 访问static修饰的方法,类变量,【默认有一个类名.】,可以省略类名
* 在没有static修饰的方法里面,
* 访问没有static修饰的方法,实例变量,可以省略this,【默认有一个this-->当前类的对象】
* 访问static修饰的方法,类变量,【默认有一个类名.】,可以省略类名
*
* 总的来说,
* 访问非static修饰的,
* 在static修饰的方法中:需要手动的创建一个对象,来访问
* 在非static修饰的方法中:可以使用this.来访问【或者省略this.】
* 访问static修饰的,默认是【类名.】 可以省略
* 因为main是static修饰的,所以在main中访问实例变量,没有static修饰的方法,需要【创建一个对象】来访问
* @param args
*/
public class BSTIterator {
private List<TreeNode> list;
private int count;
public BSTIterator(TreeNode root) {
list = new ArrayList<>();
this.inOrder(root);
count = 0;
}
public void inOrder(TreeNode root) {
if(root == null) {
return ;
}else {
this.inOrder(root.left);
list.add(root);
this.inOrder(root.right);
}
}
public int next() {
if(!hasNext()) {
throw new RuntimeException("数组越界!!!");
}
return list.get(count++).val;
}
public boolean hasNext() {
if(count >= list.size()) {
return false;
}
return true;
}
public static TreeNode initTree(Integer[] a) {
if(a == null || a.length == 0) {
return null;
}
int t = 0;
TreeNode p = new TreeNode(a[t]);
Queue<TreeNode> q = new LinkedList<>();
q.offer(p);
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(t + 1 == a.length) {
return p;
}else {
t++;
if(a[t] == null) {
node.left = null;
}else {
node.left = new TreeNode(a[t]);
q.offer(node.left);
}
}
if(t + 1 == a.length) {
return p;
}else {
t++;
if(a[t] != null){
node.right = new TreeNode(a[t]);
q.offer(node.right);
}
}
}
return p;
}
public static void main(String[] args) {
Integer[] a = new Integer[] {1, 2, 3, 4, 5, 9, 10, null, 6, 7, 8, null, null, null, 11};
TreeNode head = initTree(a);
BSTIterator it = new BSTIterator(head);
while(it.hasNext()) {
System.out.println(it.next());
}
}
}