...

View Full Version : interfaces and generics



bigdoggy
03-11-2008, 07:57 PM
hi

I am writing a generic class MinMaxArray which returns an instance of the generic class Pair comprising the min and max items from the array based on the natural order of the items. The class TestMinMaxArray is for testing


public class MinMaxArray<ArrayType extends Comparable<ArrayType>>
{
//constructor
public MinMaxArray()
{
}


public Pair MinMax(ArrayType [] array, int noOfItemsToSort)
{
int unsortedLength = noOfItemsToSort;
ArrayType max = array[0];
ArrayType min = array[0];
while(array != null)
{
for(int item=0; item<unsortedLength -1; item++)
{

if(min.compareTo(array[item+1]) > 0)
array[item+1] = min;

if(max.compareTo(array[item+1]) < 0)
array[item+1] = max;
}//for
unsortedLength --;
}//while
return new Pair<ArrayType, ArrayType>(min, max);
}//MinMax
}//class




public class Pair<FirstType, SecondType>
{
private final FirstType first;
private final SecondType second;

public Pair(FirstType requiredFirst, SecondType requiredSecond)
{
first = requiredFirst;
second = requiredSecond;
}
public FirstType getFirst()
{
return first;
}
public SecondType getSecond()
{
return second;
}
}



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class TestMinMaxArray
{
private static final int INITIAL_ARRAY_SIZE = 50;

private static final int ARRAY_RESIZE_FACTOR = 2;

public static void main(String [] args)throws IOException
{
BufferedReader systemInBufferedReader =
new BufferedReader(new InputStreamReader(System.in));

String[] lineArray = new String[INITIAL_ARRAY_SIZE];
int noOfLines = 0;
String line;

while((line = systemInBufferedReader.readLine()) != null)
{
if(noOfLines == lineArray.length)
{
String [] newLineArray
= new String[lineArray.length*ARRAY_RESIZE_FACTOR];
for(int i=0; i<lineArray.length; i++)
newLineArray[i] = lineArray[i];
lineArray = newLineArray;
}
lineArray[noOfLines] = line;
noOfLines++;
}//while
new MinMaxArray<String>().MinMax(lineArray, noOfLines);
for(int index=0; index<noOfLines; index++)
System.out.println(lineArray[index]);
}

All the three classes compile ok, but when I enter a simple sentence, I get the following run time error
Exception in thread "main" java.lang.NullPointerException
at MinMaxArray.MinMax(MinMaxArray.java:19)
at TestMinMaxArray.main(TestMinMaxArray.java:33)
Please can anybody see where my faults lie here



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum