0

I am attempting to print out a hashset taking in records from a database which are currently stored in two seperate ArrayLists. When I attempt to print out the HashSet the following error shows.

This is your HashSet[nyu.Sorting@378bf509, nyu.Sorting@7b23ec81, nyu.Sorting@15aeb7ab, nyu.Sorting@27d6c5e0, nyu.Sorting@7ef20235, nyu.Sorting@4f3f5b24, nyu.Sorting@6acbcfc0, nyu.Sorting@2d98a335, nyu.Sorting@5fd0d5ae, nyu.Sorting@16b98e56]

And this is my code:

public static HashSet<Sorting> t() {
    Sorting s = new Sorting();





    int TimeNeededOne = 75;
    int TimeNeededTwo = 75;

    int assignedTimeOne = 0;
    int assignedTimeTwo = 0;


    HashSet<Sorting> c = new HashSet<Sorting>();


        for(int i=0; i<=i1.size()-1; i++)
        {
            if((assignedTimeOne < TimeNeededOne) && !(assignedTimeOne+ i1.get(i).getLengthMins() > offensiveTimeInMins) )
            {

                c.add(i1.get(i));
                assignedTimeOne += i1.get(i).getLengthMins();

            }
        }




        for(int i=0; i<=i2.size()-1; i++)
        {
            if((assignedTimeTwo < TimeNeededTwo) && !(assignedTimeTwo + i2.get(i).getLengthMins() > TimeNeededTwo) )
            {
                c.add(i2.get(i));
                assignedTimeTwo += i2.get(i).getLengthMins();



            }
        }



        System.out.println("Training programme :" + c.size());
        System.out.println("This is your training programme" + c.toString());

    return c;
}

The c.size is there to confirm that ten entries are made which is correct however the formatting of the records from the hashset obviously contains a problem. Any help with this issue would be greatly appreciated.

Thanks.

  • No error- it's doing what you asked it to do. The problem is the objects you are echoing to the screen have no `toString()` method. – The Head Rush Aug 20 '15 at 18:52
  • http://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4/29140403 – Reimeus Aug 20 '15 at 18:53

2 Answers2

2

One way of doing this would be to override the toString() method of your Sorting class to print its contents:

public class Sorting {

    ...

    @Override
    public String toString() {
        // Return a String that represents this object
        return "...";
    }
}
John Bupit
  • 10,406
  • 8
  • 39
  • 75
1

You need override toString() method in the Sorting class, for example:

class Sorting {

    ...

    @Override
    public String toString() {
        // a string representation of Sorting object 
    }
}

java.util.Iterator runs through the whole collection and for each element invokes a toString() method. The data recorded in the java.lang.StringBuilder, which returns of its string representation at the end.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142