How to use the Comparator interface in Java? - java

I can't figure out how to properly use the Comparator interface.
NOTE: I don't want to use the "one line" comparator implementation I see on most code, meaning :
Collections.sort(deck, new Comparator<Card>() {
#Override
public int compare(Card o1, Card o2) {
return WHATEVER;
});
Again, I don't want to use this, because I'm going to be sorting many different ArrayLists and it seems like a waste of space to do that every time. I want to somehow make it work, having my compareTo method written once in one place.
I tried many different things, but I'm new to implementing interfaces, so I'm probably missing something.
This is my Card class with it's compare method. (NOTE: Let me save you some time and say that I'm not interested in using Enumerations to simplify the code and the comparison, I just want to learn how to use Comparator properly. I know it looks bad but I have to use some already written code. )
import java.util.*;
public class Card implements Comparator<Card>
{
private String number;
private int value;
private int finalValue;
private String suit;
private Player owner;
public Card(String number, String suit)
{
this.number=number;
switch (number){
case "2": this.value = 2;
break;
case "3": this.value = 3;
break;
case "4": this.value = 4;
break;
case "5": this.value = 5;
break;
case "6": this.value = 6;
break;
case "7": this.value = 7;
break;
case "8": this.value = 8;
break;
case "9": this.value = 9;
break;
case "10": this.value = 10;
break;
case "J": this.value = 11;
break;
case "Q": this.value = 12;
break;
case "K": this.value = 13;
break;
case "A": this.value = 14;
break;
}
this.suit=suit;
switch (suit){
case "Spades": this.finalValue = this.value*4;
break;
case "Hearts": this.finalValue = this.value*5;
break;
case "Clubs": this.finalValue = this.value*2;
break;
case "Diamonds": this.finalValue = this.value*3;
break;
}
}
public int compare(Card card1, Card card2)
{
Integer suitValue1;
if (card1.getSuit() == "Hearts")
suitValue1=5;
else if (card1.getSuit() == "Spades")
suitValue1=4;
else if (card1.getSuit() == "Diamonds")
suitValue1=3;
else
suitValue1=2;
Integer suitValue2;
if (card2.getSuit() == "Hearts")
suitValue2=5;
else if (card2.getSuit() == "Spades")
suitValue2=4;
else if (card2.getSuit() == "Diamonds")
suitValue2=3;
else
suitValue2=2;
Integer value1, value2;
value1 = card1.getValue();
value2 = card2.getValue();
if (suitValue1 != suitValue2)
return suitValue1.compareTo(suitValue2);
else
return value1.compareTo(value2);
}
//get methods
public int getValue()
{return this.value;}
public int getFinalValue()
{return this.finalValue;}
public String getNumber()
{return this.number;}
public String getSuit()
{return this.suit;}
public Player getOwner()
{return this.owner;}
//set methods
public void setValue(int value)
{this.value = value;}
public void setFinalValue(int finalValue)
{this.finalValue = finalValue;}
public void setNumber(String number)
{this.number = number;}
public void setSuit(String suit)
{this.suit = suit;}
public void setOwner(Player player)
{this.owner = player;}
}
So that's my compare method. Should I put it in another class or something? I try to call it using this:
Collections.sort(deck, new Comparator<Card>());
but that is obviously wrong.
deck is an ArrayList : private ArrayList<Card> deck = new ArrayList<Card>(); filled with various Card objects.

You are confusing Comparable with Comparator. They are similar of course but really fundamentally different.
Comparable defines the natural ordering of a class--how instances of your class should sort themselves by default. That's actually what you want here.
Comparator helps you to sort the instances of your class when you want to use a different sort order than the natural order. That doesn't seem to be your aim here.
So what you actually want is this:
public class Card implements Comparable<Card> {
public int compareTo(Card otherCard) {
//return 1 when this instance is greater than the parameter, -1 if less; 0 if equal
}
//Other stuff
//And make sure compareTo is consistent with equals
}
Note that the method you have to implement is compareTo, which is different from what you implement with Comparator.
Then you simply sort this way:
Collections.sort(deck)
And the cards will know how to sort themselves.
If you need more guidance, we actually did a tutorial on Comparable and Comparator with the files available on Github. Check it out if you like.

Since you seem to have one only way to compare Card objects, you don't really have to use a Comparator. Let Card implement Comparable, instead, and then sort by the 1-parameter method:
Collections.sort(deck);

To summarize:
To sort the array use Collections.sort(deck);
Your Card class needs to implement Comparable
When comparing Strings its best to use equals
It is better to use the constant String first ie "Hearts".equals(this.getSuit()), this will guard against Null pointers

You want to implement Comparable, and then you can just sort the array.

I agree with Juned, use value1.equals(value2) this returns a boolean. From the looks of things you only doing string comparison which is fairly stright forward.
Good luck.

i think this is what you intended. I don't believe you can use a switch statement on Strings unless you are 1.7+
public class Card implements Comparable<Card>
{
private String number;
private int value;
private int finalValue;
private String suit;
private Player owner;
public Card(String number, String suit)
{
this.number = number;
this.value = 0;
this.finalValue = 0;
//card value
if ("2".equalsIgnoreCase(number))
{
this.value = 2;
}
else if ("3".equalsIgnoreCase(number))
{
this.value = 3;
}
else if ("4".equalsIgnoreCase(number))
{
this.value = 4;
}
else if ("5".equalsIgnoreCase(number))
{
this.value = 5;
}
else if ("6".equalsIgnoreCase(number))
{
this.value = 6;
}
else if ("7".equalsIgnoreCase(number))
{
this.value = 7;
}
else if ("8".equalsIgnoreCase(number))
{
this.value = 8;
}
else if ("9".equalsIgnoreCase(number))
{
this.value = 9;
}
else if ("10".equalsIgnoreCase(number))
{
this.value = 10;
}
else if ("J".equalsIgnoreCase(number))
{
this.value = 11;
}
else if ("Q".equalsIgnoreCase(number))
{
this.value = 12;
}
else if ("K".equalsIgnoreCase(number))
{
this.value = 13;
}
else if ("A".equalsIgnoreCase(number))
{
this.value = 14;
}
//suits
if ("Spades".equalsIgnoreCase(number))
{
this.finalValue = this.value * 4;
}
else if ("Hearts".equalsIgnoreCase(number))
{
this.finalValue = this.value * 5;
}
else if ("Clubs".equalsIgnoreCase(number))
{
this.finalValue = this.value * 2;
}
else if ("Diamonds".equalsIgnoreCase(number))
{
this.finalValue = this.value * 3;
}
}
#Override
public int compareTo(Card o)
{
final int EQUAL = 0;
final int LESS_THAN = -1;
final int GREATER_THAN = 1;
if (this == o || this.getFinalValue() == o.getFinalValue())
{
return EQUAL;
}
else if (this.getFinalValue() < o.getFinalValue())
{
return LESS_THAN;
}
else
{
return GREATER_THAN;
}
}
// get methods
public int getValue()
{
return this.value;
}
public int getFinalValue()
{
return this.finalValue;
}
public String getNumber()
{
return this.number;
}
public String getSuit()
{
return this.suit;
}
public Player getOwner()
{
return this.owner;
}
// set methods
public void setValue(int value)
{
this.value = value;
}
public void setFinalValue(int finalValue)
{
this.finalValue = finalValue;
}
public void setNumber(String number)
{
this.number = number;
}
public void setSuit(String suit)
{
this.suit = suit;
}
public void setOwner(Player player)
{
this.owner = player;
}
}

Related

new in java method and return

i have a question. i have to create 3 methods testUreaRisk, testProteinRisk and printResults. and the below is 2 out of the 3.
public class Lab {
public static String testUreaRisk(double ureaLevel)
{
if ((ureaLevel < 0) || (ureaLevel > 10))
return "0";
else if (ureaLevel <= 4.0)
return "-1";
else
return "1";
}
public static String testProteinRisk(double proLevel)
{
if ((proLevel < 0) || (proLevel >150))
return "0";
else if (proLevel >= 67.0)
return "1";
else
return "-1";
}
so my problem is can i put a value into the return number 1, 0,-1 as -1 = low risk, 0 = cannot be defined and 1 = high risk? if can,how? because the 3rd method could only allow me to return a string that show the result (low risk,cannot be defined and high risk) instead of the number(-1,0,1).thanks
But better way is use an Enum.
Eg:
public enum Enum {
LOW("-1"), NOT_DETERMINED("0"), HIGH("1");
}
Eg:
My Enum class
public enum Enum {
LOW("-1"), NOT_DETERMINED("0"), HIGH("1");
private String code;
private Enum(String c) {
this.code = c;
}
public String getCode() {
return this.code;
}
public static Enum getEnum(String code) {
switch (code) {
case "-1":
return LOW;
case "0":
return NOT_DETERMINED;
case "1":
return HIGH;
default:
return null;
}
}
}
Now
System.out.println(Enum.getEnum(testProteinRisk(10)));
Will give you
LOW
You should go with an Enum class here. If you want to have int values, you could create in each enum a emthod that will re`enter code hereturn this value:)
Enum { LOW(-1), NOT_DETERMINED(0), HIGH(1);
// getters
}

Bluej ArrayList add

I'm trying to make a card game, and have my card class and my deck class sort of ready, it compiles ok, but when I try to run deck's method makeDeckFull, i get the output: invalidnumberinvalidnumber...
when I use the showDeck method I then see this instead of "hearts", 1
Cards#597f13c5 (i do not know what it means, or how to fix it)
Any help would be kindly appreciated: code below.
Deck Class:
import java.util.ArrayList;
public class Deck
{
private ArrayList<Cards> deck;
private int index;
public Deck()
{
deck = new ArrayList<Cards>();
}
public void makeDeckFull()
{
Cards h1 = new Cards("Hearts", 1);
Cards h2 = new Cards("Hearts", 2);
Cards h3 = new Cards("Hearts", 3);
deck.add(h1);
index ++;
deck.add(h2);
index ++;
deck.add(h3);
index ++;
//Rest of these is left out to conserve space
}
public void showDeck()
{
System.out.println(deck);
}
Card class:
public class Cards
{
private String HEARTS = "Hearts";
private String CLUBS = "Clubs";
private String DIAMONDS = "Diamonds";
private String SPADES = "Spades";
public int number;
public String suit;
public Cards()
{
suit = "unknown suit";
number = 0;
}
public Cards(String suit, int number)
{
setSuit(suit);
setNumber(number);
}
public void setCard(String suit, int number2)
{
setSuit(suit);
setNumber(number2);
}
public void setSuit(String newSuit)
{
if(
(newSuit.equalsIgnoreCase(HEARTS)) ||
(newSuit.equalsIgnoreCase(DIAMONDS)) ||
(newSuit.equalsIgnoreCase(CLUBS)) ||
(newSuit.equalsIgnoreCase(SPADES)))
{
suit = newSuit;
}
else
{
newSuit = "invalid";
System.out.print("Invalid");
}
}
public int getNumber()
{
return number;
}
public String getSuit()
{
return suit;
}
public void setNumber(int newNumber)
{
if(newNumber >0 && newNumber <=10)
{
number = newNumber;
}
else
{
number = 0;
System.out.print("invalid number");
}
}
}
1) You need to override toString() in the Cards class. As is, you are printing out the reference of the object(the gibberish) instead of the "data." You should also override the toString() method of Deck to only print out the list.
2) I'm stepping through your code snippet of makeDeckFull(), and it seems to work fine. Are you sure those three inserts are where you are getting the invalid print statements?

Counter: decrease method disregards boolean

I am trying to create a counter that holds a number that can be increased and decreased. The program also has a boolean check: when true, the counter cannot go negative. The program seems to run fine, but I cannot get the decrease methods (both decrease by one and decrease by input) to get the boolean right. It does not check the boolean value or something? I am new to Java and need help understanding what is wrong. The class is as follows:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
if (this.check = true) {
this.value = startingValue;
if (value < 0) {
value = 0;
}
}
if (this.check = false) {
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() {
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check == true) {
this.value--;
if (value < 0) {
value = 0;
}
} else if (this.check == false) {
this.value--;
}
}
public void increase(int IncreaseAmount) {
if (IncreaseAmount >= 0) {
this.value = value + IncreaseAmount;
}
}
public void decrease(int DecreaseAmount) {
if (DecreaseAmount >= 0) {
this.value = value - DecreaseAmount;
}
if (check == true && value < 0) {
value = 0;
}
}
}
Now, if I was to execute a main program with this class like this for example:
Counter count = new Counter (2, true);
count.decrease();
count.decrease();
count.decrease();
What I want my program to do is to not go negative since the boolean check is true. Yet it does go to -1. Why is this?
You fail to set the global variable check to false. You also used = instead of ==:
use:
public Counter(int startingValue, boolean check) {
this.check = check;
if (check == true) {
value = startingValue;
if (value < 0) {
value = 0;
}
}
else {
value = startingValue;
}
}
You need to use == to compare equality. The use of a single = sets the value.
Better yet, when checking the value of a boolean, just use the boolean. So instead of
if (someBool == true)
prefer
if (someBool)
Similarly, instead of
if (someBool == false)
prefer
if (!someBool)
Your boolean tests in your if statements need to use == for equality comparison in your constructor.
In your constructor's second if statement, you are assigning check to false.
When performing boolean logic with a boolean, just use the boolean.
So instead of
"if (this.check == true)" do "if (this.check)"
and
"if (this.check == false)" do "if (!this.check)"
Also, you had "if (this.check = true)" for some, which assigns true to this.check.
You main issue is that you missed an assignment of an method parameter to the object variable "this.check = check; // I added this"
Compare your version with this:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
this.check = check; // I added this
if (this.check) { //I changed this
this.value = startingValue;
if (value < 0) {
value = 0;
}
} else { //and this
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() { //good practice to use getVar and setVar, ie: getValue()
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check) { // you are not consistent with this.value VS value, which can be a confusing practise
this.value--;
if (value < 0) {
value = 0;
}
} else {
this.value--;
}
}
public void increase(int increaseAmount) { //you had "IncreaseAmount", good practice to start vars with lower case
if (increaseAmount >= 0) {
this.value = + increaseAmount;
}
}
public void decrease(int decreaseAmount) {
if (decreaseAmount >= 0) {
this.value = value - decreaseAmount;
}
if (check && (value < 0)) {
value = 0;
}
}
public void print(){
System.out.println("value:"+value+" check:"+check);
}
public static void main(String[] args) {
Counter count = new Counter (2, true);
count.decrease();
count.print();
count.decrease();
count.print();
count.decrease();
count.print();
}
}

Having problems with my Card Game in java

This is my code, my questions is with my deal method, how do I get it to inclement the to a different number every time I call it and also how to create a Boolean method. This is my code, my questions is with my deal method, how do I get it to inclement the to a different number every time I call it and also how to create a Boolean method.
package Card;
import java.util.Random;
/**
*
* #author Mr. Pierre
*/
public class Card {
private int SuitRank;
private int CardRank;
private String cardValue;
//My constructor
public Card()
{
SuitRank=1;
CardRank=2;
}
//My deal method
void dealCard()
{
SuitRank++;
Random randomGenerator = new Random();
int SuitRank = randomGenerator.nextInt(4)+1;
CardRank++;
Random randomGenerator1 = new Random();
int CardRank= randomGenerator1.nextInt(13)+2;
}
//My compare method
public int compare(Card otherCard)
{
if (otherCard.getCardRank() > CardRank)
return 1;
if (otherCard.getCardRank() == CardRank)
{
if (otherCard.getSuitRank() > SuitRank)
return 1;
if (otherCard.getSuitRank()< SuitRank)
return -1;
if (otherCard.getSuitRank()==SuitRank)
return 0;
}
if (otherCard.getCardRank() < CardRank)
return -1;
return CardRank;
}
//my Get suitrank method
public int getSuitRank()
{
SuitRank++;
return SuitRank;
}
public String getSuitName ()
{
String SuitName="";
if( SuitRank == 1){
SuitName = "Clubs";
}
else if(SuitRank == 2){
SuitName = "Diamonds";
}
else if(SuitRank == 3){
SuitName = "Hearts";
}
else if(SuitRank == 4){
SuitName = "Spades";
}
return SuitName;
}
public int getCardRank ()
{
return CardRank;
}
public String getCardName ()
{
String CardName="";
if(CardRank==2){
CardName="Duce";
}
else if(CardRank==3){
CardName="Three";
}
else if(CardRank==3){
CardName="Three";
}
else if(CardRank==4){
CardName="Four";
}
else if(CardRank==5){
CardName="Five";
}
else if(CardRank==6){
CardName="Six";
}
else if(CardRank==7){
CardName="Seven";
}
else if(CardRank==8){
CardName="Eight";
}
else if(CardRank==9){
CardName="Nine";
}
else if(CardRank==10){
CardName="Ten";
}
else if(CardRank==11){
CardName="Jack";
}
else if(CardRank==12){
CardName="Queen";
}
else if(CardRank==13){
CardName="King";
}
else if(CardRank==14){
CardName="Ace";
}
return CardName;
}
public String toString()
{
return getCardName()+ " of " +getSuitName();
}
}
int SuitRank = randomGenerator.nextInt(4)+1;
The int means you're creating a local variable instead of modyfying a class member. Also, why are you calling SuitRank++ if you're planning to set SuitRank to a random value right away? Same applies to CardRank.
As for the Boolean method - it's just public Boolean method(...).

Replace String Literals If/elseIf block with Enum

I'm new to using Java Enums and I've read that replace IF logic that compares String literals should be replaced with an Enum. I don't quite understand how to replace my below code with an Enum, any ideas? Based on the col value being passed into applyEQ, I need to do a base the next method call on it's value. I do know the possible values of col ahead of time and I'm using a constants file for now. Should I create an Enum and place it in my Interface of Constants file?
public class FilterHelper implements IFilterHelper {
private final EQuery eQuery;
public FilterHelper(EQuery query) {
eQuery = query;
}
#Override
public void applyEQ(String col, String val) throws Exception {
int return = 0;
if (col.equalsIgnoreCase(EConstants.NAME)) {
ret = Sample.addName(eQuery, val);
} else if (col.equalsIgnoreCase(EConstants.KEYWORDS)) {
ret = Sample.addKey(eQuery, val);
} else if (col.equalsIgnoreCase(EConstants.ROLE)) {
ret = Sample.addRole(eQuery, val);
}
if (return != 0) {
throw new Exception("failed");
}
}
}
EConstants.java
public final class EConstants {
public static final String NAME = "cewName";
public static final String KEYWORDS = "cewKeywords";
public static final String ROLE = "cewRole";
}
First create an enum:
public enum EConstants {
CEWNAME,
CEWROLE,
CEWKEYWORDS;
}
Then convert col String to this enum and use switch:
public void applyEQ(String col, String val) throws Exception {
int ret = 0;
final EConstants constant = EConstants.valueOf(col.toUpperCase());
switch(constant) {
case CEWNAME:
ret = Sample.addName(eQuery, val);
break;
case CEWROLE:
ret = Sample.addRole(eQuery, val);
break;
case CEWKEYWORDS:
ret = Sample.addKey(eQuery, val);
break;
default:
throw new Exception("Unhandled enum constant: " + constant);
}
}
Note that EConstants.valueOf() can throw IllegalArgumentException if col.toUpperCase() does not match any of constant values.
BTW I hate local variables initialized in multiple places (and break keyword), try extracting method:
final EConstants constant = EConstants.valueOf(col.toUpperCase());
final int ret = processSample(val, constant);
And the method itself:
private int processSample(String val, EConstants constant) throws Exception {
switch(constant) {
case CEWNAME:
return Sample.addName(eQuery, val);
case CEWROLE:
return Sample.addRole(eQuery, val);
case CEWKEYWORDS:
return Sample.addKey(eQuery, val);
default:
throw new Exception("Unhandled enum constant: " + constant);
}
}
You can rewrite your EConstants as enum:
public enum EConstants {
NAME, KEYWORDS, ROLE
}
And evaluate condition using switch statement:
// col has type of EConstants
switch (col) {
case NAME:
// do something
break;
case KEYWORDS:
// do something
break;
case ROLE:
// do something
break;
default:
// what to do otherwise
break;
}
The great thing about Java Enums is that they provide language level support for the type safe enum pattern, because among other things it allows you to define methods and even override them. So you could do this:
public enum CewColumn {
NAME("cewName") {
#Override
public int add(EQuery eQuery, String val) {
return Sample.addName(eQuery, val);
}
},
KEYWORDS("cewKeywords") {
#Override
public int add(EQuery eQuery, String val) {
return Sample.addKey(eQuery, val);
}
},
ROLE("cewRole") {
#Override
public int add(EQuery eQuery, String val) {
return Sample.addRole(eQuery, val);
}
};
private final String colName;
private MyColumn(String colName) {
this.colName = colName;
}
private static final Map<String, CewColumn> COLUMNS = new HashMap<>(values().length);
static{
for (CewColumn cewColumn : values()){
COLUMNS.put(cewColumn.colName, cewColumn);
}
}
public abstract int add(EQuery eQuery, String val);
public static CewColumn getCewColumn(String colName){
return COLUMNS.get(colName);
}
}
Then you can use it like this:
CewColumn cewColumn = CewColumn.getCewColumn(colName);
if (cewColumn != null){
int ret = cewColumn.add(eQuery, val);
}
-> You replaced the switch statement with polymorphism!
it is best to create a Enum.
public Enum AvailableCols{
COL_1,
COL_2;
}
and convert the procedure as
public void applyEQ(AvailableCols col, String val) throws Exception {
switch(col){
case COL1:
...
If you still want the string to be preserved you can see the following post
Basically create an enum and change the type of col and use equals() or == to compare the value of col against the enum values. Alternatively you could use a switch statement but I doubt that would make your code more readable for only 3 constants.
Example:
enum EConstants {
NAME,
KEYWORDS,
ROLE;
}
public void applyEQ(EConstants col, String val) throws Exception {
if( col == EConstants.NAME ) {
...
}
....
}
//or
public void applyEQ(EConstants col, String val) throws Exception {
if( EConstants.NAME.equals(col) ) { //col might be null
...
}
....
}
//or
public void applyEQ(EConstants col, String val) throws Exception {
switch( col ) {
case NAME:
...
break;
case ROLE:
...
}
}
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
If your raw data is a string, you will still need to do a string comparison to assign the enum. This might be faster if you do a lot of comparisons on the result data, but if not, it simply adds complication to your code.
You can iterate over the values of the enum like a collection, which gives you an advantage when you need to add constants. That's not bad.
Here is how to do it:
public enum EConstants {
NAME, KEYWORDS, ROLE
}
...
public EConstants setConstant(String from) {
if (from.equalsIgnoreCase("cewName")) {
return NAME;
} else if (col.equalsIgnoreCase("cewKeywords")) {
return KEYWORDS;
} else if (col.equalsIgnoreCase("cewRole")) {
return ROLE;
}
}
You preprocess your data that way and now when you are trying to figure out logic you can use a switch on the enum type value.
Here is a trick for you. No switch/case (just come up with a better name for EConstants).
public enum EConstants {
NAME,
KEYWORDS,
ROLE;
private interface Applier {
void apply(EQuery query, String val);
}
public void apply(EQuery query, String val) {
map.get(this).apply(query, val);
}
private static Map<EConstants, Applier> map = new HashMap<EConstants, EConstants.Applier>();
static {
map.put(NAME, new Applier() {
#Override
public void apply(EQuery query, String val) {
Sample.addName(query, val);
}
});
map.put(KEYWORDS, new Applier() {
#Override
public void apply(EQuery query, String val) {
Sample.addKey(query, val);
}
});
map.put(ROLE, new Applier() {
#Override
public void apply(EQuery query, String val) {
Sample.addRole(query, val);
}
});
}
}
Now you just write:
#Override
public void applyEQ(EConstants econs, String val) {
econs.apply(equery, val);
}

Categories

Resources