The code block is listed below:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
This is the Vertex class:
public class Vertex implements Comparable<Vertex> {
public int arcWeight;
public int preDelay;
public boolean infinite = true;
public int nodeDelay = 0;
public Vertex predecessor = null;
public ArcNode firstArc = null;
public int mark = 0;
public int starTime;
public int finishTime;
public ArrayList<ArcNode> inArcList = new ArrayList<ArcNode>();
public ArrayList<ArcNode> outArcList = new ArrayList<ArcNode>();
}
Actually, I just want to copy the element in AdjList to a new array subgraph. But the error message shows that "java.lang.NullPointerException" and shows the problem lies in "subGraph[i].nodeDelay = AdjList[i].nodeDelay;" line.
I tested by printing to the console. And found the AdjList.length is 8 and the problem occurs in the very first round; And even when I only write "subGraph[i].nodeDelay;" without assigning any value to it, it also shows the wrong message.
Any idea on this? Thanks in advance.
Add it inside the loop:
subGraph[i] = new Vertex();
You first need to instantiate an object (subGraph[i] in your case) before accessing it.
The answer is: uninitialized variable. You did initialize subGraph to be an array, but you did not initialize subGraph[i].
When you create an object array in java, it's automatically initialized with null values. It's your responsibility to loop on the array an populate it with references to new objects.
In your case, you should assign Vertex objects to all array positions.
You need to create a Vertex instance and place it in the array prior to setting any fields.
Something like:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
subGraph[i] = new Vertex(); // adding instance prior to setting fields.
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
On add
subGraph[i] = new Vertex();
before this line
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
Because subGraph[i] is initially null . So subGraph[i].nodeDelay will obviously throw a NullPointerException, because you are trying to access or modify the field of a null object. Array of references will always be initialized with elements of null references by default.
Related
I am initalizing several objects of the same type that have a common field:
public class Example {
private static objectCounter = 1;
public Example () {
objectCounter++;
}
}
Since these objects are created with a for loop like this
for (int i = 0; i<5; i++) {
Example e = new Example();
}
they are not referenced.
Is there a way to get a specific object based on objectCounter value ?
Something like
//get the Example object with objectCounter==2
get(2);
Thank you
My suggestion will be saving into array:
Example store[] = new Example[5]
for (int i = 0; i<5; i++) {
store[i] = new Example();
}
And then , search for the specific object.
As stated in the comments, a static value will persist through all instances of your class.
If you want your Example to "know" it's identity, pass it in when you construct it:
Example:
public class Example {
private int id;
public Example (int val) {
this.id = val;
}
// Getters/setters
}
Probably also want to add your objects to a list to access them later, so before your for-loop:
List<Example> examples = new ArrayList()<Example>;
And create them like this:
for (int i = 0; i<5; i++) {
Example e = new Example(i);
examples.add(e);
}
I have a task to change a type of a variable into ArrayList and I need to initialize it as an ArrayList. I don't know how to do it :(
I tried this in a such way:
private ArrayList<T> warehouseContent = new ArrayList<T>();
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.size()
+ products.length];
int i = 0;
for (; i < warehouseContent.size(); i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.size()]);
}
warehouseContent=updatedWarehouseContent;
}
But I think it isn't correct. The source code which I need to change is below:
private WarehouseItem[] warehouseContent = new WarehouseItem[0];
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.length
+ products.length];
int i = 0;
for (; i < warehouseContent.length; i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.length]);
}
warehouseContent=updatedWarehouseContent;
}
Could someone give me any tips or explain me what I need to use here a generic type ArrayList?
Start by declaring the warehouseContent type as a list of WarehouseItem:
private List<WarehouseItem> warehouseContent = new ArrayList<>();
Now you can rely on ArrayList's built-in ability to grow in your registerProducts method:
public void registerProducts(Product... products) {
for (Product product : products) {
warehouseContent.add(new WarehouseItem(product));
}
}
This one loop does what the two loops and an allocation of your original implementation did. Note that copying the content of an old array into the new one is still there, but it is encapsulated in the add method of ArrayList.
I am relatively new to java, and this is only the second time I have ever tried to design a program that has an array of class objects. I am having trouble because when I go into debug mode, it is showing me that the arrays are being built correctly. However, when I try to build a string or even print to the console, I am getting a null pointer exception.
I am trying to make an array of Slot class objects.
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
Slot[] s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
And the Slot class has its own array, block[], constructed by a value passed in through its constructor.
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
short block[] = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Later in the program I then try to print to the console or build a string and it always breaks when I try to use any element in the slot[] in the C class.
Have I instantiated and initialized my 2 different arrays correctly?
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
Try something like these instead
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Replace
short block[] = new short[byteSize];
with
block = new short[byteSize];
Always use a this operator to initialize in a constructor so that you may differentiate clearly between local variables and instance variables
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
this.block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
I'm trying to make a game for my Java class, but I keep getting a NPE. I know that it means one of the variables being passed is a null, but I have no idea where. I have checked all variables involved. I believe it may be an issue with initializing the arrays, but I'm still not seeing what I've done wrong. I've checked around stack overflow and I have seen NPEs due to various reasons, but I can't find a solution that works on mine.
public class Inventory{
public int gold = 0;
private Item[] itemListArray = new Item[30];
private JButton[] itemButtonArray = new JButton[30];
private JButton buttonBack = new JButton("Back");
private static final String HOME = "Home";
public Inventory() {
for(int i = 1;i < 31; i++)
{
itemListArray[i].emptySlot = true; //Here is where the NPE hits
}
}}
That is where the NPE calls for the error
public class Item {
protected String name = "";
protected int def = 0;
protected int stack = 100;
protected boolean stackable = false;
protected boolean consume = false;
boolean emptySlot = true;
protected ImageIcon icon;
public Item(){
}
public boolean isArmor()
{
if(def >= 1)
{
return true;
} else {
return false;
}
}
public boolean isConsumable()
{
if(consume = true)
{
return true;
} else {
return false;
}
}
public boolean isEmpty()
{
if(emptySlot = true)
{
return true;
} else {
return false;
}
}
Here is the declaration of Item.
Please Answer soon to my issue, I can't seem to figure it out.
Item[] itemListArray = new Item[30];
This code just creates an array that contains null values, you need to initializes each individual value in the array.
for(int i = 1;i < 31; i++)
{
itemListArray[i].emptySlot = true; //Here is where the NPE hits
}
And this cycle will cause ArrayIndexOutOfBoundsException later because in Java valid array indexes start from 0 and go to array.length-1 (0 to 29 in your case), while this code will try to access itemListArray[ 30 ].
It isn't sufficient for you to instantiate your array, you must also populate it with objects. Otherwise each index contains null by default.
private Item[] itemListArray = new Item[30];
for (int i = 0; i < itemListArray.length; i++) {
itemListArray[i] = new Item();
}
You instantiate your array with private Item[] itemListArray = new Item[30]; which creates an array of type Item with 30 null entries.
When you call itemListArray[i].emptySlot in your loop in the constructor you are accessing a variable from a null object.
You will have to instantiate any Item objects in your array in the loop in your constructor (or elsewhere) before you can access any variables or invoke any methods from them.
Also your for loop is skipping the first element. The first element in Java has an index of 0.
I guess you may haven't understand initialization in java.you just initialize a array ,but it haven't refer to the real object.
code like this will help:
for(int i = 1;i < 31; i++){
Item item = new Item();
item.emptySlot = true;
itemListArray[i] = item; //Here is where the NPE hits
}
try to use a constructor in Item class is much better,hope it work.
Creating an array of objects defaults all of them to null. You need to put an object into each element of the array to get rid of this problem.
for (int i = 0; i < itemListArray.length; i++) {
itemListArray[i] = new Item();
}
for (int j = 0; j < itemButtonArray.length; j++) {
itemButtonArray[j] = new JButton();
}
I'm trying to copy an Object I've created from one array to another of the same type in Java. When I run my program I receive a NullPointerException.
The relevant class functions are:
private int mState;
public Cell(int pRow, int pColumn, int pState) {
//other things
setState(pState);
}
public void setState(int pNewState) {
mState = pNewState;
}
public void setDead() {
mState = DEAD;
}
and the line in which the error occurs:
mFutureGeneration[i][j].setDead();
That array is defined as
private Cell [][] mFutureGeneration;
then dimensioned as
mFutureGeneration = new Cell[100][100];
It receives its contents from:
Cell [][] vSeedArray = new Cell[100][100];
which is filled as
for (int i = 0; i<100; i++) {
for (int j = 0; j<100; j++) {
int vNewState = mGenerator.nextInt(2) - 1;
vSeedArray[i][j] = new Cell(i,j,vNewState);
}
}
I think the problem is happening in the copy, but I was always under the impression Java copied by reference, so I can't see why it would be failing.
I copy the contents across with a loop
for(int i = 0; i<vSeedArray.length; i++) {
for(int j=0; j<vSeedArray[i].length; j++) {
mCurrentGeneration[i][j] = vSeedArray[i][j];
}
}
Any help would be appreciated.
Thanks.
I'm not sure you're ever allocating any "Cell" objects - just the array to hold them.
If so, that's probably the cause of your NullPointer exception.
Good link:
http://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm
Scroll down to the section "Array of Objects".
'Hope that helps!