-1

So here is my code

    public static void main(String[] args)
     {
        ArrayList<Event> pairs = new ArrayList<Event>();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        for (int i = 0; i < n; i++)
        {
          int x = sc.nextInt();
          int y = sc.nextInt();
          pairs.add(new Event(x, y));
        }

        Collections.sort(pairs);

        for(int i = 0; i < pairs.size(); i++)
        {
          System.out.println(pairs.get(i));
        }
     }

I wanted to see that the .in file I gave it with this info

4
5 7
7 8
8 4
4 5

would be sorted correctly, but I wanted to print it out. When I went to try and print it though I got these values in return.

C:\Users\Kneer\Documents\CS2\SCroll>java Main < test.in
Main$Event@5a01ccaa
Main$Event@71c7db30
Main$Event@19bb089b
Main$Event@4563e9ab

am I traversing the Arraylist info incorrectly?

Dingle Box
  • 53
  • 3
  • What is the `Event` class? You probably want to add a `.toString` method to it (or getters for `x` and `y`, and use those). Please provide a [mcve]. – geocodezip Oct 17 '20 at 17:53
  • You're printing an object, which would print "ObjectName@HashCode" (check [this](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4)) – Arvind Oct 17 '20 at 17:54

2 Answers2

0

I think your Event class doesn't have any toString() implementation. If you add it, it should print whatever your toString() implementation prints.

If you look at java.lang.Object toString() implementation, it will be clear why it's printing these hex values -

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, the solution would be to override the toString() method and return your custom formatted object as String.

shakhawat
  • 2,639
  • 1
  • 20
  • 36
0

Override the Event.toString() method or create an eventToString(Event evt) method that you can access.

public static String eventToString(Event evt) {
  return "Event["+evt.x +"," +evt.y+"]";
}

then you can use it in your current code:

for(int i = 0; i < pairs.size(); i++) {
      System.out.println(eventToString(pairs.get(i)));
}