Assume that you write an application to filter data. For example, to get the data of a given range in an integer array, write a method to remove the data that does not meet the conditions in the array and return a new array.
How can we implement this method? One method is:
Import java. util .*;
Public class ZeroDemo1 {
// Filter input array and throw away values
// That are less than minval or greater
// Maxval
Static int [] filterData (int indata [], int minval, int maxval ){
// Check parameters for errors
If (indata = null ){
Throw new NullPointerException ("indata is null ");
}
If (maxval <minval ){
Throw new IllegalArgumentException ("maxval <minval ");
}
// Count number of valid values
// In input array
Int validcnt = 0;
For (int ii = 0; ii <indata. length; ii ++ ){
If (indata [ii]> = minval & indata [ii] <= maxval ){
Validcnt ++;
}
}
// If no valid values, return null
If (validcnt = 0 ){
Return null;
}
// Copy valid values to new array
// And return it
Int outdata [] = new int [validcnt];
For (int ii = 0, j = 0; ii <indata. length; ii ++ ){
If (indata [ii]> = minval & indata [ii] <= maxval ){
Outdata [j ++] = indata [ii];
}
}
Return outdata;
}
Public static void main (String args []) {
// Set up test array of integers
Int indata [] = new int [] {1, 3,-17, 8, 59 };
// Filter out values not in the range 1-10
Int outdata1 [] = filterData (indata, 1, 10 );
For (int ii = 0; ii <outdata1.length; ii ++ ){
System. out. println (outdata1 [ii]);
}
// Filter out values not
// In the range 100-200
Int outdata2 [] = filterData (
Indata, 100,200 );
For (int ii = 0; ii <outdata2.length; ii ++ ){
System. out. println (outdata2 [ii]);
}
}
}
The filterData method traverses the input array twice and calculates the number of valid data for the first time. Initialize a new array based on the data and copy the valid data. If no valid data exists, the method returns null.
The execution result of ZeroDemo1 is:
1
3
8
Exception in thread "main"
Java. lang. NullPointerException
At ZeroDemo1.main (ZeroDemo1.java: 72)
This is a very simple application. When filterData is called for the second time, null is returned, and an exception is thrown.
If there is no valid data, there is a better implementation method:
/*
If (validcnt = 0 ){
Return null;
}
*/
If no valid data exists, we can allocate a zero-length array:
Int