I seem to be having trouble with a particular Java method, involving arrays and
ID: 3798166 • Letter: I
Question
I seem to be having trouble with a particular Java method, involving arrays and File objects. I would appreciate any revised editions or suggestions on how to improve my flawed code segment, shown below, with the method contract and method itself shown below:
/**
* This method creates and returns a new array that contains a list of the
* unique File objects that occur in the files array. For this method,
* File objects are the same if they are equal using the .equals method.
* (The returned array is the set of file objects.)
*
* The size of the returned list is determined by the number of unique
* items in the original list. The order of the items in the returned
* list is unspecified.
*
* The files array must not contain null.
*
* (Hint: This problem also has two major steps. Solve them one at a
* time, and don't try to mix the code between the two steps. (Keep the
* ideas and code steps separate as you can.) Additionally, the code for
* each step is very similar.
*
* (Warning: You cannot use Java collections, or any other built-in class
* that helps build sets. Figure out your own way to see if the array has
* duplicates in it.)
*
* @param files An array of File objects, possibly containing duplicates
* @return An array of unique File objects
* @throws NullPointerException If files is null or files contain null
*/
public static File[] getUniqueSet(File[] files)
{
// Find size of unique File objects array
int filesLength = files.length;
for (int i = 0; i < filesLength; i++)
{
for (int j = i + 1; j < files.length; j++)
{
if (files[i].equals(files[j]))
files[j] = files[filesLength - 1];
}
}
File[] uniqueFiles = new File[filesLength + 1];
int uniquePos = 0;
// Add unique files to array uniqueFiles, avoiding duplicates
for (int i = 0; i < files.length; i++)
{
for (int j = i + 1; j < files.length; j++)
{
if (i != j && (! files[i].equals(files[j])))
{
uniqueFiles[uniquePos] = files[j];
uniquePos++;
}
}
}
return uniqueFiles;
}
}
Explanation / Answer
public static File[] getUniqueSet(File[] files)
{
// Find size of unique File objects array
int uniqueFileCount=0;
if(files.length!=null)
{
int filesLength = files.length;
for (int i = 0; i < filesLength; i++)
{
if(files[i]!=null)
uniqueFileCount++;
for (int j = i + 1; j < files.length; j++)
{
if(files[j]!=null)
if (files[i].equals(files[j]))
files[j] = null;
}
}
File[] uniqueFiles = new File[uniqueFileCount];
int uniquePos = 0;
// Add unique files to array uniqueFiles, avoiding duplicates
for (int i = 0; i < files.length; i++)
{
if(files[i]!=null){
uniqueFiles[uniquePos]=files[i];
uniquePos++;
}
}
}
return uniqueFiles;
}
}