0

My code should add 3 Objects of type "Location" to the List "locations" I declared right under

public class myClass extends JFrame {

static List<Location> locations = new ArrayList<Location>();

This is the part that SHOULD add to the List:

locations.add(new Location(new Point(1,1), "Test1", travelLocations.Moon));
locations.add(new Location(new Point(2,2), "Test2", travelLocations.Planet));
locations.add(new Location(new Point(3,3), "Test3", travelLocations.Asteroidfield));

And this is my Location class:

import java.awt.Point;

public class Location {
    static Point coordinate;
    static String name;
    static travelLocations type;

    public Location(Point curLoc, String name, travelLocations locType) {
        coordinate = curLoc;
        locName = name;
        type = locType;
    }
}

What it does: It adds the Location called "Test3" three times, everytime I add a Location it adds one and overwrites every allready in this List. I know, it looks similar to other questions on Stackoverflow, but I compared them and tried those with similar problems and no solution worked for me. I'm sure it is just a small thing and there is an easy solution, but I can't see it. Thank you in advance.

  • 1
    remove static from the Location variables. – isaace Apr 25 '18 at 20:16
  • 1
    The list works fine, the problem is that the attributes of your `Location` class are `static`. – Turing85 Apr 25 '18 at 20:16
  • To help understand the problem, marking those class members as `static` means there is only copy of them for ALL instances of the class. You're adding different instances, but updating data they share, and "test3" is the last update you make. As others have said, delete the `static` keyword and you should be fine. Check out https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class – brabster Apr 25 '18 at 20:18
  • Beside that every individual part works fine, so I did not forget to import something. – HexadiemsnionalerAlp Apr 25 '18 at 20:18
  • thank you for your fast reply, I test it as soon I can – HexadiemsnionalerAlp Apr 25 '18 at 20:18

1 Answers1

1

That is because you declared your fields static, meaning there is only one copy of them in your class

klido
  • 98
  • 1
  • 7