Null Pointer Exception

Hi,

I've been trying to figure out for the last few hours why I got this error but to no avail. I can't see which part of my code is pointing to null. If anyone can point out what's wrong and how to correct it please let me know. Here is the whole code, with the /*** ***/ highlighting the lines of code which the compiler is showing as part of the null pointer exception - It's highlighted 4 errors. I do know it has something to do with the line of code (highlighted) Collections.sort(modifiedOffSpring); and not anything to do with Collections.sort(populatn); .

publicclass Population{

public Database d =new Database();

public Random rand =new Random();

publicstatic ArrayList population =new ArrayList();

publicstatic ArrayList parents =new ArrayList();

publicstatic ArrayList children =new ArrayList();

publicvoid initialPopulation(){

double[] reuters ={

8.0, 9.0, 12.5, 11.5, 6, 7, 4, 2, 3, 4, 3, 5, 5.5};

Share s1 =new Share(reuters);

d.addShare(s1);

for (int i = 0; i < 12; i++){

Chromosome chr =new Chromosome(rand);

chr.setDatabase(d);

population.add(chr);

System.out.println("Chromosome Weights are: " + chr);

System.out.println("Chromosome Fitness Value is: " + chr.fitness(0));

System.out.println();

}

}

public ArrayList tournamentSelection(int tournamentSize){

ArrayList contenders =new ArrayList();

for (int n = 0; n < (population.size()); n = (n + tournamentSize)){

int j = 0;// pointer variable to keep contender's indexes 0-4 fixed for adding population elements

// Check that sample of 5 can be taken from population

if ( (n + tournamentSize) < population.size() ||

(n + tournamentSize) == population.size()){

for (int i = n; i < n + tournamentSize; i++){// Get as many chromosomes as specified by tournament size (which is 5)

contenders.add(j, population.get(i));

j++;

}

// Sort the sub-population in order of fitness (ascending order)

Collections.sort(contenders);

// Return the best two Chromosomes with the lowest fitness

parents.add(contenders.get(0));

parents.add(contenders.get(1));

for (int k = tournamentSize; k > 0; k--){

contenders.remove(k - 1);// remove all elements from contenders to start over and receive the next sample of tournamentSize

}

}

else{//If sample of 5 cannot be taken from population, break to terminate from first/outter for loop

break;

}

}

//for(int i=0; i<parents.size(); i++){

// System.out.println("parents "+ i+ " " + parents.get(i));}

// System.out.println("contenders"+contenders.toString());

return parents;

}

public ArrayList crossOver(ArrayList intermediateGen,double crossOverRate){//crossOverRate between 0.7 and 0.95, intermediateGen are the parents

//Shuffle parents to exclude any chance of bias

Collections.shuffle(intermediateGen,new Random());

for (int i = 0; i >< parents.size(); i++){

System.out.println("parents " + i +" " + parents.get(i));

}

for (int p = 0; p < parents.size() - 1; p = p + 2){

double random = rand.nextDouble();//Get a value between 0.0 and 1.0

if (random < crossOverRate || random == crossOverRate){// If value generated is less than or equal to crossOverRate, apply cross-over

int crossOverPoint = (rand.nextInt(11) + 1);//The cross over point is generated randomly, and must occur between bit index 1 and bit index 11 of the parent Chromosomes so that an actual cross-over will always occur.

System.out.println("Crossover Point " + crossOverPoint);

int[] childStart =newint[12];

int[] childFinish =newint[12];

int[] childStart2 =newint[12];

int[] childFinish2 =newint[12];

// Child one

//Copying bits before cross-over point from first parent

for (int j = 0; j < crossOverPoint; j++){

childStart[j] = ( (Chromosome) intermediateGen.get(p)).bit[j];

}

// Copying bits after cross-over point from second parent

for (int k = crossOverPoint; k < childFinish.length; k++){

childFinish[k] = ( (Chromosome) intermediateGen.get(p + 1)).bit[k];

}

children.add(new Chromosome(childStart, childFinish));//Creation of new child Chromosome

System.out.println("children list c1" + children.toString());

//Child two

//Copying bits before cross-over point from second parent

for (int m = 0; m < crossOverPoint; m++){

childStart2[m] = ( (Chromosome) intermediateGen.get(p + 1)).bit[m];

}

//Copying bits after cross-over point from first parent

for (int n = crossOverPoint; n < childFinish2.length; n++){

childFinish2[n] = ( (Chromosome) intermediateGen.get(p)).bit[n];

}

children.add(new Chromosome(childStart2, childFinish2));//Creation of new child Chromosome

System.out.println("children list c2" + children.toString());

}

else{//If no cross-over, then children are exact copies of their parents

System.out.println("No crossover this time");

children.add(parents.get(p));

children.add(parents.get(p + 1));

}

}

System.out.println("Children list in total " + children);

return children;

}

public ArrayList mutation(ArrayList offSpring,double mutationRate){//Mutation rate between 1% and 5%

int[] bitMutate =newint[1];

for (int i = 0; i < (offSpring.size()); i++){//Iterate through each Chromosome

System.out.println("Traversing through new Chromosome");

for (int k = 0; k < 12; k++){//Iterate through each bit of Chromosome

double random = rand.nextDouble();//Get a value between 0.0 and 1.0 for each bit

System.out.println("Random value as a % is " + (random * 100) +"%");

if (random < mutationRate || random == mutationRate){//If value generated is less than or equal to mutation rate, apply mutation

System.out.println("Mutation needed here");

bitMutate[0] = ( (Chromosome) offSpring.get(i)).bit[k];//Get bit and store its weight value temporarily into bitMutate

System.out.println("bit " + (k + 1) +" is of weight value " +

bitMutate[0]);

bitMutate[0] = rand.nextInt(6);//Mutate bit by generating a new weight value between 0 and 5

if (bitMutate[0] == ( (Chromosome) offSpring.get(i)).bit[k]){

System.out.println("New mutated weight is the same as original weight, therefore mutation will be applied again.");

bitMutate[0] = rand.nextInt(6);

}//If mutated value generated is the same as the weight value already in the chromosome, then generate a new mutated weight value

System.out.println("mutated weight value is now " + bitMutate[0]);

( (Chromosome) offSpring.get(i)).bit[k] = bitMutate[0];//Replace the corresponding bit value with the mutated bit value

System.out.println(

"Corresponding Chromosome bit value has been mutated to " +

( (Chromosome) offSpring.get(i)).bit[k]);

}

else{

System.out.println("No Mutation needed here.");

}

}

}

return offSpring;//Arraylist returned with new mutated values in the genes

}

publicvoid reinsertion(ArrayList populatn, ArrayList modifiedOffSpring){

Collections.sort(populatn);

System.out.println(populatn.toString());

Collections.sort(modifiedOffSpring);/****** ERROR *****/

//System.out.println(modifiedOffSpring.toString());

}

publicstaticvoid main(String args[]){

// Population p = new Population();

// p.initialPopulation();

// p.tournamentSelection(5);

}

}

publicclass Chromosome

implements Comparable{

int[] bit =newint[12];

Database db;

public Chromosome(Random rand){

for (int i = 0; i < 12; i++){

bit[i] = rand.nextInt(6);

}

}

public Chromosome(int[] cs,int[] cf){

for (int i = 0; i < cs.length; i++){

if (cs[i] == 0){}

else{

bit[i] = cs[i];

}

}

for (int j = 0; j < cf.length; j++){

if (cf[j] == 0){}

else{

bit[j] = cf[j];

}

}

}

public String toString(){

String result ="";

for (int i = 0; i < 12; i++){

result = result + bit[i] +",";

}

return result;

}

publicvoid setDatabase(Database d){

db = d;

}

publicdouble fitness(int share){

double prediction = 0;

int divisor = 0;

Share sh = db.getShare(share);/****ERROR****/

for (int i = 0; i < 12; i++){

prediction = prediction + bit[i] * sh.getPrice(i);

divisor = divisor + bit[i];

}

if (divisor != 0){

prediction = prediction / divisor;

}

else{

prediction = 0;

}

// System.out.println("Prediction Value is: " + prediction);

double actualPrice = sh.getPrice(12);

return Math.abs(prediction - actualPrice);

}

//Used for comparing the fitness values of each Chromosome object in the contender ArrayList for tournament selection in the Population class

publicint compareTo(Object otherChromosomeObject)throws ClassCastException{

if (! (otherChromosomeObjectinstanceof Chromosome)){

thrownew ClassCastException("A Chromosome object expected.");// Throws exception if objects being compared are not both of type Chromosome

}

Chromosome otherChromosome = (Chromosome) otherChromosomeObject;

if (this.fitness(0) < otherChromosome.fitness(0)){/****** ERROR ****/

return -1;

}

if (this.fitness(0) > otherChromosome.fitness(0)){

return 1;

}

return 0;

}

}

publicclass GenAlg{

publicstaticvoid main(String[] args){

/* Database d = new Database();

double[] dd = {

8.0, 9.0, 12.5, 11.5, 6, 7, 4, 2, 3, 4, 3, 5, 5.5};

Share s1 = new Share(dd);

d.addShare(s1);

ArrayList population = new ArrayList(); */

Population p =new Population();

p.initialPopulation();

p.tournamentSelection(5);

p.crossOver(p.parents, 0.9);

p.mutation(p.children, 0.05);//5 is the tournament selection size

p.reinsertion(p.population, p.children);/***** ERROR *****

// Random rand = new Random();

/* for (int i = 0; i < 10; i++) {

Chromosome c = new Chromosome(rand);

c.setDatabase(d);

population.add(c);

System.out.println("Chromosome Weights are: " + c);

System.out.println("Chromosome Fitness Value is: " + c.fitness(0));

System.out.println();

System.out.println(population.size());

System.out.println(population.toString());

}

*/

}

}

publicclass Share{

double[] prices =newdouble[13];

public Share(double[] pr){

prices = pr;

}

double getPrice(int i){

return prices[i];

}

}

import java.util.ArrayList;

import java.util.Random;

publicclass Database{

ArrayList sharedatavalues =new ArrayList();

publicvoid addShare(Share s){

sharedatavalues.add(s);

}

public Share getShare(int i){

return (Share) sharedatavalues.get(i);

}

}

[21933 byte] By [Niru99a] at [2007-11-26 23:51:49]
# 1
It's the VM, not the compiler, that's giving you the error.Paste in the complete, exact error message and stack trace.
jverda at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 2

Ok Sure it says:

Exception in thread "main" java.lang.NullPointerException

at Chromosome.fitness(Chromosome.java:52)

at Chromosome.compareTo(Chromosome.java:77)

at java.util.Arrays.mergeSort(Unknown Source)

at java.util.Arrays.sort(Unknown Source)

at java.util.Collections.sort(Unknown source)

at Population.reinsertion(Population.java:184)

at GenAlg.main(GenAlg.java:19)

Niru99a at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 3

> Ok Sure it says:

>

> Exception in thread "main"

> java.lang.NullPointerException

>

> at Chromosome.fitness(Chromosome.java:52)

> at Chromosome.compareTo(Chromosome.java:77)

> at java.util.Arrays.mergeSort(Unknown Source)

> at java.util.Arrays.sort(Unknown Source)

> at java.util.Collections.sort(Unknown source)

> at Population.reinsertion(Population.java:184)

> at GenAlg.main(GenAlg.java:19)

Okay, so, you're calling Collections.sort, which ends up calling your compareTo method, which, at line 77, calls fitness. In fitness, at line 52, you're getting the NPE. Assuming that's this line: Share sh = db.getShare(share); /****ERROR****/

then db must be null.

jverda at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 4

> Ok Sure it says:

>

> Exception in thread "main"

> java.lang.NullPointerException

>

> at Chromosome.fitness(Chromosome.java:52)

> at Chromosome.compareTo(Chromosome.java:77)

> at java.util.Arrays.mergeSort(Unknown Source)

> at java.util.Arrays.sort(Unknown Source)

> at java.util.Collections.sort(Unknown source)

> at Population.reinsertion(Population.java:184)

> at GenAlg.main(GenAlg.java:19)

which line is line 52 in Chromosome? also, why does your compareTo method manually check for the correct type, then manually throw a ClassCastException? no need to bother with that, just let it happen on its own. and your method need not declare it throws ClassCastException either

georgemca at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 5
Yes, however I don't understand why Collections.sort(populatn); is working correctly because that's doing exactly the same procedure - ie calling Collections.sort which calls compareTo, which calls fitness, and yet Collections.sort(modifiedOffSpring); is giving an error?
Niru99a at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 6

> which line is line 52 in Chromosome? also, why does

> your compareTo method manually check for the correct

> type, then manually throw a ClassCastException? no

> need to bother with that, just let it happen on its

> own. and your method need not declare it throws

> ClassCastException either

OK, line 52 is Share sh = db.getShare(share);

Niru99a at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 7

> > which line is line 52 in Chromosome? also, why

> does

> your compareTo method manually check for the

> correct

> type, then manually throw a ClassCastException? no

> need to bother with that, just let it happen on its

> own. and your method need not declare it throws

>ClassCastException either

> OK, line 52 is Share sh = db.getShare(share);

as jverd already worked out, dammit!

georgemca at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 8

> Yes, however I don't understand why

> Collections.sort(populatn); is working correctly

> because that's doing exactly the same procedure - ie

> calling Collections.sort which calls compareTo, which

> calls fitness, and yet

> Collections.sort(modifiedOffSpring); is giving an

> error?

Read reply 3. sort calls compareTo (though maybe not directly).

The stack trace shows you what calls what calls what.

jverda at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 9

>

> Read reply 3. sort calls compareTo (though maybe not

> directly).

>

> The stack trace shows you what calls what calls what.

OK, thanks. In the end I took the Collections.sort(modifiedOffSpring); as I found it wasn't necessary, however, I've just programmed all the stuff now, and a very similar null pointer exception is coming up. The stack trace is:

Exception in thread "main" java.lang.NullPointerException

at Chromosome.fitness(Chromosome.java:49) // Share sh = db.getShare(share);

at Chromosome.compareTo(Chromosome.java:74)//if (this.fitness(0) < otherChromosome.fitness(0)) {

at java.util.Arrays.mergeSort(Unknown Source)

at java.util.Arrays.sort(Unknown Source)

at java.util.Collections.sort(Unknown source)

at Population.reinsertion(Population.java:68) //Collections.sort(contenders);

at GenAlg.main(GenAlg.java:29)

Any ideas on how to fix this error? I have added to the code (not much though) - I doubt that code would have had the null pointer error? If you need to see the whole complete code let me know. Really can't figure out how to fix this, even though I followed through and understood the stack trace. Thanks

Niru99a at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 10
that DB object is not being initialized. initialize it
georgemca at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 11
Forgot to add that my db isn't null(?) or am I missing something here? I'm lost now with how to correct the exception.
Niru99a at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 12
OK, do I do something like Database db = new Database()? Or do I feed it values?
Niru99a at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...
# 13
> OK, do I do something like Database db = new> Database()? Or do I feed it values?I suspect that at some point something should be calling Chromosome. setDatabase. it's the Chromosome instance that's not got a Database object
georgemca at 2007-7-11 15:30:57 > top of Java-index,Java Essentials,Java Programming...