Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Problem with Ordering an Arraylist of Comparable Objects.

  1. #1
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Problem with Ordering an Arraylist of Comparable Objects.

    I know I posted this problem in another thread but I thought it would be more appropriate to put it here, if one of the mods wants to close the other thread that's fine.

    Basically I have a Video Poker game and I order the hand to make identifying pairs, straights etc easier.

    However it seems to order hand objects in other classes which is absolutely confounding me, here are the classes and relevent code:

    Card
    public class Card implements Comparable<Card>
    {
    	protected int rank;
    	protected int suit;
     
    	protected String[] suitStrings = {"Clubs", "Diamonds", "Spades", "Hearts"};
    	protected String[] rankStrings = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"};
     
     
    	public Card(int a, int b)
    	{
    		if (a >= 0 && a <= 3);
    		{	
    			suit = a;
    		}
    		if (b <= 12 && b >= 0);
    		{
    			rank = b;
    		}
    	}
     
    	public int getRank()
    	{
    		return rank;
    	}
    	public int getSuit()
    	{
    		return suit;
    	}	
     
    	public String suitAsString()
    	{
    		return suitStrings[suit];
    	}
     
    	public String rankAsString()
    	{
    		return rankStrings[rank];
    	}
     
    	public String cardAsString()
    	{
    		String value;
    		value = rankStrings[rank] + " of " + suitStrings[suit];
    		return value;
    	}
     
    	public String cardValueAsShortString()
    	{
    		String value;
    		value = suit + "_" + rank;
    		return value;
    	}
     
    	public int compareTo(Card c)
    	{
    		int result;
    		if(rank != c.getRank())
    			result = rank - c.getRank();
    		else
    			result = suit - c.getSuit();
     
    		return result;
    	}
     
    }



    CardCollection
    import java.util.ArrayList;
    import java.util.Collections;
     
    public class CardCollection
    {
     
    		public ArrayList<Card> cards = new ArrayList<Card>();
     
             	public CardCollection()
    		{}
     
     
    		public void orderCards()
    		{
    			Collections.sort(this.cards);
    			System.out.println("ORDER");
    		}
     
     
    		public void printCollectionLong()
    		{
    			for(int i = 0; i < cards.size(); i++)
    			{
    				System.out.print(cards.get(i).cardAsString() + ", ");
    				if(i%5 == 4)
    				System.out.print("\n");
    			}
    			System.out.print("\n\n\n\n");
    		}
     
     
     
    	}

    Hand
    public class Hand extends CardCollection
    {
     
    	public void replaceCard(int i, Card c)
    	{
    		cards.remove(i);
    		//cards.add(i,c);
    		cards.add(c);
    	}
    }



    VideoPoker
    public class VideoPoker 
    {
    	public CardDeck deck;
    	public Hand playerHand, h2;
    	protected StrengthChecker sc;
     
    	public int determineStrength()
    	{
    		System.out.println("detStr 1:");
    		playerHand.printCollectionLong();
    		h2 = playerHand;
    		sc = new StrengthChecker(h2);
     
    		System.out.println("detStr 2:");
    		playerHand.printCollectionLong();
    		sc.setStrength();
     
    		System.out.println("detStr 3:");
    		playerHand.printCollectionLong();
    		h2.printCollectionLong();
    		deck.printCollectionLong();
    		return sc.getStrength();		 
    	}
     
    }

    I put h2 in here for test purposes on the first run through the prints in the first block are in random order while the ones in the second are in order(not what I want) and the hands in the third are in order but the deck is not.

    Also a new deck is initialised after the first deal of a game. However the print in the first block of determineStrength are always in order after the first run through.

    StrengthChecker
    public class StrengthChecker 
    {
    	Hand hand1;
    	Hand hand2;
    	int strength;
     
    	public StrengthChecker(Hand h)
    	{
    		hand1 = h;
    		hand2 = h;
    		System.out.println("SC cons 1:");
    		hand2.printCollectionLong();
    		hand1.orderCards();
    		System.out.println("SC cons 2:");
    		hand2.printCollectionLong();
    	}
     
    	public int getStrength()
    	{
    		return strength;
    	}
     
    	public void setStrength()
    	{
    		if (isStraightFlush() == true)
    			strength = 8;
    		else if (Has4OfKind() == true)
    			strength = 7;
    		else if (isFullHouse() == true)
    			strength = 6;
    		else if (isFlush() == true)
    			strength = 5;
    		else if (isStraight() == true)
    			strength = 4;
    		else if (Contains3OfAKind() == true)
    			strength = 3;
    		else if (Contains2Pair() == true)
    			strength = 2;
    		else if (ContainsPair() == true)
    			strength = 1;
    		else
    			strength = 0;
    		}
    }

    As a test I put in the second hand and invoked it's method to check the order of the cards the first time before I order hand1 hand2 shows the cards in a random order however afterwards it is ordered this really doesn't make sense to me since I only invoked hand1's orderCards method.

    There are other methods and variables but I put in everything I think is relevent to this problem.

    Now this is the first time I've tried to order objects in an array so maybe it's not unusual but it sure as hell has me stumped any help is appreciated. And sorry for the lack of comments just something I never got into(keep meaning to but I keep forgetting )


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    Have you tried debugging the code by adding some println() statements to see what is happening and how the values of variables are changing? Since your problem is with things in the wrong order, start with the compareTo() method. Make sure its giving the correct results.

  3. The Following User Says Thank You to Norm For This Useful Post:

    Faz (June 9th, 2010)

  4. #3
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    Fairly basic stuff, I did try that a load of places but the compareTo() method didn't occur to me. Tried it out and it helped me identify the problem it was in the GUI class I made, a bit of a hangover from a way I was planning on implementing.
        public void mousePressed(MouseEvent e) 
    	{
        	int x = e.getX();
        	int y = e.getY();
        	if(x > DECK_X && x < DECK_X + CARD_WIDTH && y > DECK_Y && y < DECK_Y + CARD_HEIGHT)
        		{
        		game.deal();
        		repaint();
        		game.determineStrength();//This is the line that caused the problem as deal invokes it as well.
        		}

    Cheers man.

    Now how do I change the title to show this is solved.
    Last edited by Faz; June 9th, 2010 at 05:12 PM.

  5. #4
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    Thread Tools -> Mark this thread as solved

    You can find this at the top of the page.

    // Json

  6. The Following User Says Thank You to Json For This Useful Post:

    Faz (June 13th, 2010)

  7. #5
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    Cheers man.

    I have it seems messed up though and left it a bit too hastily. I was positive I checked and that it sorted a hand once but it turns out I didn't have the determineStrength method anywhere in the deal method
    This is the secondDeal method
    	public void secondDeal()
    	{
    		int winnings;
    		System.out.println("secondDeal");
     
    		for(int i=0; i<5;i++)
    		{
    			if (held[i] == false)
    			{
    				playerHand.replaceCard(i, deck.dealTopCard());
    				System.out.print(i+":"+held[i]);
    			}
    			held[i] = false;
    		}
     
    		winnings = returns[determineStrength()] * bet; // This is a new line
     
    		increaseCredit(winnings);
    		stageOne = true;
    	}

    and this is the modified determineStrength method
    	public int determineStrength()
    	{
    		sc = new StrengthChecker(playerHand);
     
    		//System.out.println("detStr 2:");
    		//playerHand.printCollectionLong();
    		sc.setStrength();
     
    		//System.out.println("detStr 3:");
    		//playerHand.printCollectionLong();
    		//h2.printCollectionLong();
    		//deck.printCollectionLong();
    		if (sc.getStrength() == 0 && sc.getImpCardH().getRank() < 9)
    			return 0;
    		else
    			return sc.getStrength();		 
    	}

    I mean my understanding of what happens here is that I create a StrengthChecker object called sc which then has a Hand object hand1 which is distinct to playerHand from the VideoPoker object so why are both being sorted when I invoke
    hand1.orderCards();

    Argh I was full sure I had it before I must have just wanted it to be right so much I tricked myself

    EDIT: Is it something to do with clone() and implements Cloneable? I'm just trying that out but I seem to be getting the same result.
    Last edited by Faz; June 13th, 2010 at 12:17 PM.

  8. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    Is it something to do with clone() and implements Cloneable
    how are you using those?

  9. #7
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    OK well I've just gone back to it tonight it seems mad to me I've tried a few ways. At the moment I have this bit of code in there to see if it will work.
    		//h2 = new Hand(playerHand.getCards());
    		//h2 = new Hand(playerHand.clone());
    		h2 = playerHand.clone();playerHand.printCollectionLong();//I've tried this way and the two above all to the same effect
    		h2.orderCards();
    		playerHand.printCollectionLong();

    This is the Hand class
    import java.util.ArrayList;
    import java.util.Collections;
    //import java.util.Comparator;
    //import java.io.Serializable;
     
    public class Hand extends CardCollection implements Cloneable
    {
    	public Hand()
    	{}
     
    	public Hand clone() 
    	{
    		System.out.println("ADAFEGSDVBBH BNSF");
    		Hand c = new Hand();
                    c.setCards(this.getCards());
                    return c;
             }
     
    	public Hand(Hand another) 
    	{
    		this(another.getCards()); // you can access  
    		System.out.print("RAR2");
     
    	}
     
    	public Hand(ArrayList<Card> c) 
    	{
    		this.setCards(c);
    	}
     
    	public void replaceCard(int i, Card c)
    	{
    		cards.remove(i);
    		cards.add(i,c);
    	}
    }

    Every time the println statements show the playerHand to have been sorted even though I only called the method orderCards in h2.

  10. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    Add more println() statements to show who is calling the method to do the sorting.

  11. #9
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Re: Problem with Ordering an Arraylist of Comparable Objects.

    Ah I got it, I think . At least everything seems to be working how I would expect it I had tried doing a similar thing with the cards but not quite both together which seems to have worked like so.

    I created a constructor for Hand that took in an ArrayList of cards
    	public Hand(ArrayList<Card> c) 
    	{
    		cards.clear();
    		int i = 0;
    		while(i<c.size())
    		{
    			cards.add(c.get(i));
    			i++;
    		}
    	}

    Haha I'm just looking at my code I thought I had did something with the Card class but now I can see I didn't this seems to work I mean it's sorting the arraylist I expect it to and no others as you can see it was by passing the cards one by one rather then just using the whole thing all a bit odd and contrary to how I assumed it would work.

    I mean if you had say
    x = 5;
    y = x;
    y += 5;
    Then y would be 10 but x would still be 5 I guess it's different for objects.

    Anyways that problem has taken up more time then the rest of the code I'll probably try to jazz it up a bit now work on a few graphics or something. I'll post it to the café at some stage too if anyone wants to take a look at it.

Similar Threads

  1. Comparable Interface
    By yelrubk in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 28th, 2010, 09:08 AM
  2. looping through an ArrayList of objects with their own attributes
    By etidd in forum Java Theory & Questions
    Replies: 2
    Last Post: April 2nd, 2010, 06:15 AM
  3. Arraylist Objects to Database
    By frankycool in forum JDBC & Databases
    Replies: 3
    Last Post: November 15th, 2009, 08:01 PM
  4. How can i store ArrayList objects in Access database
    By frankycool in forum JDBC & Databases
    Replies: 0
    Last Post: November 4th, 2009, 12:44 AM
  5. Object creation from a input file and storing in an Array list
    By LabX in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: May 14th, 2009, 03:52 AM