import java.io.BufferedReader;
import java.util.Collections;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import com.javaranch.common.TextFileIn;
public class SortNames
{
public static class CelebrityNamesFile
{
public String firstName;
public String lastName;
public static class CompareLastName implements Comparator< CelebrityNamesFile >
{
@Override
public int compare( CelebrityNamesFile o1, CelebrityNamesFile o2 )
{
return o2.lastName.compareTo( o1.lastName );
}
}
public static void main( String[ ] args ) throws IOException
{
ArrayList< CelebrityNamesFile > myCelebrityList;
myCelebrityList = new ArrayList< CelebrityNamesFile >();
TextFileIn celebrityNamesFile = new TextFileIn( "celebrityNamesFile.txt" );
boolean doneReadingCelebrityNames = false;
while ( ! doneReadingCelebrityNames )
{
String oneName = celebrityNamesFile.readLine();
if ( oneName == null )
{
doneReadingCelebrityNames = true;
}
$ Eclipse doesn't like the add statement that follows, to wit: The method add (SortNames.CelebrityNamesFile) in the type ArrayList(SortNames.CelebrityNamesFile)is not applicable for the arguments (String)
else
{
myCelebrityList.add( oneName );
}
}
celebrityNamesFile.close();
$ And then it doesn't like my sort statement, to wit: Bound mismatch: The generic method sort(List T) of type Collections is not applicable for the arguments (ArrayList (SortNames.CelebrityNamesFile)). The inferred type SortNames.CelebrityNamesFile is not a valid substitute for the bounded parameter (T extends Comparable(? super T))
Collections.sort( myCelebrityList );
System.out.println( myCelebrityList );
Collections.sort( myCelebrityList, new CelebrityNamesFile.CompareLastName() );
System.out.println( myCelebrityList );
}
}
}
What am I doing wrong? I have read many posts here, have read the Java docs regarding comparator, have read Java tutorials regarding comparator. Head First Java, Ivor Horton's beginning Java 7. Still clueless.
The purpose of the program is to read names from a txt file, add them to an arraylist, print the arraylist in its natural order, sort the arraylist by last name, print the list again.
For the first issue, the problem is fairly simple. oneName
is a String
, and myCelebrityList
is a collection of CelebrityNamesFile
- which means that you can only add objects to the collection of type CelebrityNamesFile
.
For the second issue, your problem is that the CelebrityNamesFile
class does not implement the Comparable
interface. Sorting requires that an ordering is implemented for the list element type, e.g. by implementing Comparable
for the class or providing a Comparator
to the sort
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With