多语言展示
当前在线:1567今日阅读:26今日分享:39

this和 NullPointerException

今天中午写了一个程序,这个程序的构造方法里的参数名和类的属性名是一样的,然后这个地方就产生了歧义,因此在程序运行中一直出现 java.lang.NullPointerException。
工具/原料
1

eclipse-luna

2

win732bit and jdk1.7

方法/步骤
1

源程序:package ch2.divide;import java.util.Collections;import java.util.Comparator;import java.util.Vector;import ch1.incremental.Greater;/* * 在学习使用之前首先应该注意的是在这个堆的创建初期本身就是一个最大顶堆  * 之后的所有操作都是作为一个最大(小)的顶堆 存在使用的 * */public class PrioQueue { private Vector heap; private int heapSize; Comparator comp; public PrioQueue(){ heapSize=0; heap=new Vector(); comp=new Greater(); } public PrioQueue(Comparator comp){ heapSize=0; heap=new Vector(); //this.comp=comp; } public void enQueue(Comparable e){ int i=heapSize++; heap.add(e); while((i>0)&&comp.compare(heap.get(i),heap.get(MyTool.parent(i)))>0){ Collections.swap(heap, MyTool.parent(i), i); i=MyTool.parent(i); } } public Comparable deQueue(){ if(heapSize<1){ return null; } Comparable  top = heap.get(0); heapSize--; heap.set(0, heap.get(heapSize));  //将末尾的值放在开头  改变堆的样子 交换 heap.remove(heapSize); ///将末尾的值删除掉 ////这个地方的heap本身就是部分成立 最大顶二叉堆的。 MyTool.heapify(heap, 0, heapSize,comp); return top; } public boolean empty(){ return heapSize<=0; } }

2

测试程序:package ch2.divide;import ch1.incremental.Greater;import ch1.incremental.Less;public class TestQueue { public static void main(String[] args) { Integer a[] = { 5, 1, 9, 4, 6, 2, 0, 3, 8, 7 }, i; String b[] = { 'ChongQing', 'ShangHai', 'AoMen', 'TianJin', 'BeiJing', 'XiangGang' }; Double c[] = { 8.5, 6.3, 1.7, 9.2, 0.5, 2.3, 4.1, 7.4, 5.9, 3.7 }; PrioQueue q = new PrioQueue(); PrioQueue q1 = new PrioQueue(new Less()); PrioQueue q2 = new PrioQueue(new Greater()); for (i = 0; i < 10; i++) { q.enQueue(a[i]); q2.enQueue(c[i]); } for (i = 0; i < 6; i++) q1.enQueue(b[i]); while (!q.empty()) System.out.print(q.deQueue() + ' '); System.out.println(); while (!q1.empty()) System.out.print(q1.deQueue() + ' '); System.out.println(); while (!q2.empty()) System.out.print(q2.deQueue() + ' '); System.out.println(); }}

3

出错内容以及问题代码

4

修改内容

5

输出正确,改错成功

注意事项
1

注意在java构造方法中的一个小常识要合理的使用this指针

2

尽量不要让属性名和参数名重名

推荐信息