File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Really strange behavior in an ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Really strange behavior in an ArrayList" Watch "Really strange behavior in an ArrayList" New topic

Really strange behavior in an ArrayList

Kevin Cuzner

Joined: Apr 13, 2009
Posts: 1
I am making a small program for one of my CS classes that basically demonstrates mastery of java and programming and such. I have been programming for slightly over a decade, so I assumed that as long as I read the manual I would do fine. This program lets the user create shapes on a board, drag them around, and resize them. I have all of those operations working except for a small bug in the dragging that I cannot seem to work out.

I use an arraylist to store all my shapes that are currently being displayed. At all times the shapes have to be depth sorted with the lowest y values being at the back. To do this I created a Comparable which does a comparison on the shape's position. I then sort the Arraylist using this every time I make a change to the positions of the shapes. However, if I click on a shape with a high y value and move it up, it then acts like a kind of pushbar and pushes all shapes that match it's y at any given time to keep going with it. I don't understand how this can happen. My code can only support modifying one object at once, but it seems to be modifying all objects that don't match a certain condition. Can anyone explain this to me?

EDIT: I just commented out the sort lines and it works properly. That points to the sorter as the culprit. Can a sorter place two items "next" to eachother in a 1D array like an ArrayList? That doesn't exactly seem intuitive.

My MouseAdapter and Comparator (they are inside a class which contains the ArrayList shapes along with the booleans fill and mode:
Martijn Verburg

Joined: Jun 24, 2003
Posts: 3275

Hi Kevin and welcome to Javaranch!

A couple of random hints

1.) What does the Javadoc for ArrayList say about maintaining order?
2.) Have you printed out the contents of your ArrayList before/after you sort? What happens?

Let us know how you get on!

Cheers, Martijn - Blog,
Twitter, PCGen, Ikasan, My The Well-Grounded Java Developer book!,
My start-up.
I agree. Here's the link:
subject: Really strange behavior in an ArrayList
It's not a secret anymore!