I'm creating a FriendList which extends ArrayList and is populated with a Friend object. However when I try accessing methods normally available to Friend, the compiler says it cannot resolve the method - in this case compareTo(Friend).
FriendList class:
public class FriendList<Friend> extends ArrayList<Friend> {
private boolean isAdded;
public FriendList() {
isAdded = false;
}
public void alphabetAdd(Friend friend) {
if (this.isEmpty()) {
add(friend);
return;
}
int index = 0;
// add friends alphabetically
while (!isAdded) {
Friend f = this.get(index+1);
if (f.compareTo(friend) < 0) {
index++;
} else {
this.add(index, friend);
isAdded = true;
}
}
}
}
Friend class:
public class Friend implements Comparable<Friend> {
// constructors and other methods work fine - just need to see compareTo
// #Override
public int compareTo(#NonNull Friend o) {
String name1 = getUserFirstName() + getUserLastName();
Friend f;
if (o instanceof Friend) {
f = (Friend) o;
String name2 = f.getUserFirstName() + f.getUserLastName();
if (name1.compareTo(name2) < 0)
return -1;
else if (name1.compareTo(name2) > 0)
return 1;
}
return 0;
}
}
The issue is in FriendList<Friend>. This is treated as a declaration of generic class like FriendList<T> and Friend becomes not an actual type but an alias that is why only methods declared in Object are available.
Change declaration of your class to
public class FriendList extends ArrayList<Friend>
Related
I need to sort a java list containing objects of type Hotel
List<Hotel> hotelList = new ArrayList<>();
Inside the class I do have the method
#Override
public List<Room> getAvailableRooms() {
return this.rooms;
}
I need to sort my hotelList by the price attribute found in Room class.
Any suggestions?
You should either use a Comparator or implement the Comparable interface
public class Foo implements Comparable<ToSort> {
private int val;
public Foo(int val){
this.val = val;
}
#Override
public int compareTo(ToSort f) {
if (val > f.val) {
return 1;
}
else if (val < f.val) {
return -1;
}
else {
return 0;
}
}
Read more here
https://dzone.com/articles/sorting-java-arraylist
i dont understand why there is an error(The method findNodeByNode(ITreeNode<>) is undefined for the type NODETYPE) in my for loop. A college has exactly the same code, but he has no errors?
Please help me
public class GenericTreeNode<NODETYPE> extends Object implements ITreeNode<NODETYPE> {
NODETYPE nodeValue;
String label;
private LinkedList<NODETYPE> children;
public GenericTreeNode(String label, NODETYPE value)
{
this.label=label;
this.nodeValue=value;
children= new LinkedList<NODETYPE>();
}
public boolean checkNodeByValue(NODETYPE value) {
if(this.nodeValue.equals(value))
{
return true;
}
else
return false;
}
public ITreeNode<NODETYPE> findNodeByValue(NODETYPE searchValue) {
if(this.checkNodeByValue(searchValue))
{
return this;
}
if(this.isLeaf())
{
return null;
}
long length = this.children.size();
int i;
for(i=0; i < length; i++)
{
this.children.get(i)).findNodeByValue( searchValue);
}
return null;
}
You have two consecutive parentheses:
get(i))
Change the sentence by:
this.children.get(i).findNodeByValue( searchValue);
findNodeByValue(...) belongs to the class GenericTreeNode<NODETYPE>, but you are calling it on an instance of NODETYPE in your LinkedList<NODETYPE>. You can only call it on an instance of GenericTreeNode<NODETYPE> (or just call it if doing it on this instance of the class)
I have a class called classes who has this compareto method:
#Override
public int compareTo(Object other) {
Cours ot = (Cours)other;
String heure2 = ot.heure;
int autre = Integer.parseInt(heure2.substring(0,2));
int le = Integer.parseInt(this.heure.substring(0,2));
if (autre > le) {
return 1;
}
if (autre == le) {
return 0;
} else {
return -1;
}
}
I have another class called day that has a list of classes :
private List<Cours> journee;
And a method to sort the classes:
public void TrieListe() {
Collections.sort(journee);
}
When I use TrieListe() everything works fine, I can sort the list.
But I've added another class called Weeks which contains a List of Days
And now I want to use TrieList() from that class :
private List<Days> leWeek;
public void TrieListe() {
Collections.sort(leWeek);
}
So how can I use my compareTo method from my classes class using sort() in my Weeks class.
Create a new abstract class AComparableByHour and make your classes extend it.
public abstract class AComparableByHour implements Comparable<AComparableByHour> {
public abstract String getHeure();
// Your comparison method goes here
#Override
public int compareTo(AComparableByHour ot) {
String heure2 = ot.getHeure();
int autre = Integer.parseInt(heure2.substring(0,2));
int le = Integer.parseInt(this.getHeure().substring(0,2));
if( autre > le){
return 1;
}
if( autre == le){
return 0;
} else {
return -1;
}
}
}
public class Cours extends AComparableByHour {
// This method is mandatory now.
// You could move it to the new superclass
public String getHeure() {
return heure;
}
...
}
public class Days extends AComparableByHour {
public String getHeure() {
return heure;
}
...
}
I have a class called classes who has this compareto method:
#Override
public int compareTo(Object other) {
This is already wrong. Your class should implement Comparable<classes> (noting that classes is a truly terrible name for a class, for at least three separate reasons), which will force the method signature to be:
#Override
public int compareTo(classes other) {
In a Gate class I have method public List<Signal> inspect(List<Signal> inputs) which should contain a combination of feed(), propagate(), and read(). That's the only method I have left to finish but getting an error. Could smb please help me with this method? NOTE: propagate() is left abstract to be overriden by childclasses of Gate class. The method public List<Signal> inspect(List<Signal> inputs) should combine feed(), propagate(), and read().
import java.util.*;
public abstract class Gate implements Logic {
private List<Wire> inputs;
private Wire output;
private String name;
public Gate(String name, List<Wire> ins, Wire out)
{
this.name = name;
this.output = out;
if(ins.size() == 0 || ins.isEmpty())
throw new ExceptionLogicParameters(false, 1, 0);
else
this.inputs = ins;
}
#Override
public void feed(List<Signal> inSigs)
{
if(inSigs.size() != inputs.size())
throw new ExceptionLogicParameters(false, inputs.size(), inSigs.size());
else
{
for(int i = 0; i < inSigs.size(); i++)
{
inputs.get(i).setSignal(inSigs.get(i));
}
}
}
#Override
public void feed(String name)
{
if(!(this.name.equals(name)))
throw new ExceptionLogicMalformedSignal(name.charAt(0), "Invalid logic input");
else
{
Signal signalValue = Signal.fromString(name.charAt(0));
}
}
#Override
public List<Signal> read()
{
List<Signal> signals = new ArrayList<>();
signals.add(output.getSignal());
return signals;
}
#Override
public abstract boolean propagate();
#Override
public List<Signal> inspect(List<Signal> inputs)
{
List<Signal> allMethods = new ArrayList<>();
allMethods.add(this.feed(inputs));
allMethods.add(this.propagate());
allMethods.add(this.read());
}
#Override
public String toString()
{
return this.name+"( " + inputs.toString() + " | " + output.toString() + " )";
}
#Override
public boolean equals(Object other)
{
if(other instanceof Gate)
{
Gate someGate = (Gate)other;
return (this.inputs == someGate.inputs) && (this.output.equals(someGate.output)
&& (this.name.equals(someGate.name)));
}
else
return false;
}
}
All your methods have no return type.
When you do this
allMethods.add(this.feed(inputs));
allMethods.add(this.propagate());
allMethods.add(this.read());
It would not return anything and hence nothing is added to the list which will throw error.
Your list of of type signal
List<Signal> allMethods = new ArrayList<>();
You need to change the return type of all methods to Signal to add them to the list. Like you cant add an Integer to a List<String> you cannot add anything else than type Signal to the List<Signal>
I'm no sure of your code logic and if you can change the return type or not, but changing all methods return type to Signal should work fine.
Also, you need a return statement for
public List<Signal> inspect(List<Signal> inputs)
You have to always return something if method is not void and the return type should be same as function type
As a project for university, I am writing a Java program that takes classes derived from a Player class and stores them in a Club class. The Club is a cricket club (hence the variable/class names). The class below is still only partially built but it compiles and is complete enough in regards to the issue I need resolving. I am receiving two 'unchecked' warnings when compiling the class below:
import java.util.*;
public class Club{
private String name;
private List<Player> players;
private Set<Player> playersAverage;
private int regID;
#SuppressWarnings(value = {"unchecked"})
public Club(){
this.name = "";
this.players = new ArrayList<Player>();
this.playersAverage = new TreeSet<Player>(new BattingAverageComparator());
this.regID = 1;
}
#SuppressWarnings(value = {"unchecked"})
public Club(String name){
this.name = name;
this.players = new ArrayList<Player>();
this.playersAverage = new TreeSet<Player>(new BattingAverageComparator());
this.regID = 1;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public boolean registerPlayer(Player player) throws UninitialisedObjectException, NullPointerException{
if(!(validPlayer(player))){
throw new UninitialisedObjectException("attempted to add an uninitialised player object to Club.players");
}
if(!(this.players.contains(player))){
player.setRegID(this.regID);
this.regID++;
for(int i = 0; i < this.players.size(); i++){
if(player.compareTo(this.players.get(i)) > 0){
this.players.add(i,player);
return true;
}
}
}
return false;
}
public boolean removePlayer(Player player) throws NullPointerException{
return this.players.remove(player);
}
public String getPlayerDetails(int regID) throws InvalidRegistrationIDException{
String s = "";
for (int i=0; i < this.players.size(); i++){
if (this.players.get(i).getRegID() == regID){
s = this.players.get(i).toString();
break;
}
}
if(s == ""){
throw new InvalidRegistrationIDException("getPlayerDetails() attempted on invalid regID");
}
return s;
}
private boolean validPlayer(Player player){
return player.getFirstName()!="" || player.getLastName()!="" || player.getAge()>0 || player.getHeight()>0 || player.getWeight()>0;
}
public void averages(BattingAverageComparator compareAveragesOf){
}
}
Using the following Comparator:
import java.util.*;
public class BattingAverageComparator implements Comparator{
public int compare(Object obj1,Object obj2) throws IllegalArgumentException{
if(!(obj1 instanceof Player) || !(obj2 instanceof Player)){
throw new IllegalArgumentException("BattingAverageComparator cannot compare objects that are not of, or do not extend, the Player class.");
}
Player thisPlayer = (Player) obj1;
Player thatPlayer = (Player) obj2;
if(thisPlayer.getDismissals() == 0 && thatPlayer.getDismissals() == 0){
if(thisPlayer.getRuns() > thatPlayer.getRuns()){
return 1;
}
else if (thisPlayer.getRuns() < thatPlayer.getRuns()){
return -1;
}
else{
return thisPlayer.compareTo(thatPlayer);
}
}
else if(thisPlayer.getDismissals() == 0 && thatPlayer.getDismissals() > 0){
return -1;
}
else if(thisPlayer.getDismissals() > 0 && thatPlayer.getDismissals() == 0){
return 1;
}
else{
double thisAverage = thisPlayer.getRuns()/thisPlayer.getDismissals();
double thatAverage = thatPlayer.getRuns()/thatPlayer.getDismissals();
if(thisAverage > thatAverage){
return 1;
}
else if(thisAverage == thatAverage){//need to make a double threshold
return 0;
}
else{
return -1;
}
}
}
public boolean equals(Object obj){
return obj instanceof BattingAverageComparator;
}
}
The following warning appears for both constructors:
Club.java:13: warning: [unchecked] unchecked conversion found : BattingAverageComparator
required: java.util.Comparator<? super Player>
this.playersAverage = new TreeSet<Player>(new BattingAverageComparator());
Is there anyway to fix this other than suppressing the warning?
If you need any more information I will post it. There are quite a few classes in the program and I see no need to post them all at present.
The problem is here:
public class BattingAverageComparator implements Comparator{
You declare this as a raw comparator, but you are feeding in a generic type of <Player>
So change it to
public class BattingAverageComparator implements Comparator<Player>{
Yep, use generic type:
public class BattingAverageComparator implements Comparator<Player>{
public int compare(Player obj1,Player obj2){
//etc.
}
}