I am having some trouble looping through an array with objects, inside the class. I wrote a little demo here so you can follow:
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
So, I have an array with the type Tank. Then I call the method doStuff inside the Tank class. The method takes the array and loops through it. And then I want to do stuff to every tank that is not the current instance of the class. I hope you can make sense out of my code and this description.
The problem is that I get nullPointerException for if (tanks[i].equals(this))
What am I doing wrong here?
That means that tanks[i] is null. (or that your overridden equals() method has a bug)
You need to check for that.
if you want to compare the IDs of your object you can use == instead of .equals()
doStuff(Tank tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i] == this) {
continue;
}
// Do stuff
}
}
When I run this code:
public class Tank {
public static void main(String[] args) {
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
}
public void doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
}
No error happens. Therefore, you've probably overridden .equals, and that is where the NullPointerException is occurring. The other possibility is that your simple example doesn't accurately reflect where your bug is occurring.
Related
private ArrayList<Suspect> accomplices = new ArrayList<Suspect>();
public void checkAndAddAccomplice(Suspect aSuspect) {
for(int i=0; i<aSuspect.getAccomplices().size(); i++) {
if(!(aSuspect.getName().equals(aSuspect.getAccomplices().get(i).toString()))) {
accomplices.add(aSuspect);
}
}
}
This is the code and i dont know why but the array stays empty even after this method.
This is starting to become really frustrating.
you should be comparing aSuspect.getName() with aSuspect.getAccomplices().get(i).getName(), instead of aSuspect.getAccomplices().get(i).toString()
if(!(aSuspect.getName().equals(aSuspect.getAccomplices().get(i).getName()))) {
First i add new Popotnik in List popotnik depending on how big it is, which is working fine - function prostaMesta. Then i want to go through list popotnik and set popotnik value depending on where it is in for, but value of i will always be 0 everytime it is being called. Also i have break there as i only want to set one popotnik at the time. How should i increment (i) while having some sort of break in there?
Also if(popotnik.get(i) == null){} is not being called, but values inside popotnik are null(s)
private List<Popotnik> popotnik = new ArrayList<Popotnik>();
public void prostaMesta(List<Popotnik> popotnik, int sedez){
stanovanje.setPostle(sedez);
for(int i=0; i<stanovanje.getPostle(); i++){
popotnik.add(new Popotnik());
}
System.out.println(popotnik);
}
public void dodajPotnika(List<Popotnik> popotnik, Popotnik popotnik2){
for(int i=0; i<popotnik.size(); i++){
if(popotnik.get(i) == null){
setPopotnik(popotnik, i);
popotnik.set(i, popotnik2);
break;
}
}
System.out.println(getPopotnik());
}
public void setPopotnik(List<Popotnik> popotnik, int i){
this.popotnik = popotnik;
}
public List<Popotnik> getPopotnik(){
return popotnik;
}
Main class:
List<Popotnik> alPopotnik = new ArrayList<Popotnik>();
if(x.equals("p")){ //inside of a loop when prostaMesta() is being called
potovanje.prostaMesta(alPopotnik, sedez);
}
`if(x.equals("d")){` //inside of a loop when dodajPotnika() is being called
System.out.println("Vnesi ime: ");
String ime = skener.next();
Popotnik popotnik = new Popotnik(ime);
potovanje.dodajPotnika(alPopotnik, popotnik);
}
The if(popotnik.get(i) == null) is never true because objects on the list are not null. You initialize them in the for loop in prostaMesta.
If you have some fields inside the Popotnik class then they are null, but object itself is not.
You would need to do something like popotnik.get(i).getName() == null.
Besides, if you only want to add a number at the end of popotnik's name then it isn't necessary to initialize a list with empty objects.
You could just add objects to list using a different constructor.
For example popotnik.add(new Popotnik("Popotnik"+(popotnik.size()+1))).
It's not pretty but I think initialization like this here is not necessary.
I am trying to add an object of type Car to an Array of cars, I do not have a specific index within the array that I want the car to go into, I just want to add the car to the first empty and available index that doesn't have a car object already in there. Here is my code:
protected static final int MaxCars = 5;
protected Car[] cars = new Car[MaxCars];
public void addCar(Car c)
{
for(int i = 0; i < MaxCars; i++)
{
if (cars[i] == null)
{
cars[i] = c;
break;
}
}
incrementNumInTeam();
}
On the if statement inside the for loop I am getting the a NullPointerException .. how can I overcome this?
Your variable cars is likely null at the time the if block is called. Your error is present but likely elsewhere in your code. Check to be sure that you're not shadowing the cars variable and that the variable being initialized is the same one being read.
So I'm creating a class called dicegame. Here's the constructor.
public class dicegame {
private static int a, b, winner;
public dicegame()
{
a = 0;
b = 0;
winner = 2;
}
And now in the main, I'm creating an array of this object (I called it spaghetti for fun).
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[10];
spaghetti[1].roll();
}
But when I try to do anything to an element in the array, I'm getting the NullPointerException. When I tried to print one of the elements, I got a null.
You created an array, but you have to assign something (e.g. new dicegame()) to each element of the array.
My Java is slightly rusty, but this should be close:
for (int i=0; i<10; i++)
{
spaghetti[i] = new dicegame();
}
new dicegame[10]
just creates an array with 10 empty elements. You still have to put a dicegame in each element:
spaghetti[0] = new dicegame();
spaghetti[1] = new dicegame();
spaghetti[2] = new dicegame();
...
You need spaghetti[1]=new dicegame() before you call roll() on it.
Right now you are allocating an array,but don't. Place any objects in this array, so by default java makes them null.
1.you have just declared the array variable but not created the object yet. try this
2.you should start index with zero not with one.
dicegame[] spaghetti = new dicegame[10]; // created array variable of dicegame
for (int i = 0; i < spaghetti.length; i++) {
spaghetti[i] = new dicegame(); // creating object an assgning to element of spaghetti
spaghetti[i].roll(); // calling roll method.
}
Firstly,you should create object for every spaghetti input of yours.
You can start with whatever value you want. Just be sure that the size of array is matched accordingly so that you won't get ArrayIndexOutOfBounds Exception.
So,if you wanted to start with 1 and have 10 objects of the class dicegame,you will have to assign the size of the array as 11(since it starts from zero).
your main function should be like :
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[11];
//the below two lines create object for every spaghetti item
for(int i=1;i<=11;i++)
spaghetti[i]=new dicegame();
//and now if you want to call the function roll for the first element,just call it
spaghetti[1].roll;
}
Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)