0

I need to get a value from an array list. The objects in the list stores some values in variables (x- and y-coordinates).

I tried to use the get()-function but it only returns a string like this: linkTrackerTest$Object@20e76e47.

In addition I tried thinks like objects.get(0(x)) but nothing worked yet.

Could anybody help me with this?

Thank in advance :-)

sln
  • 83
  • 1
  • 2
  • 9
  • 2
    Have you tried `objects.get(0).x `? – MaxPower Jul 12 '17 at 16:04
  • 1
    Possible duplicate of [How do I print my Java object without getting "SomeType@2f92e0f4"?](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – OH GOD SPIDERS Jul 12 '17 at 16:11
  • Can you please post a [mcve] that shows the behavior in as few lines as possible? Note that this should not be your whole sketch. It should be a small example that we can copy and paste to see the problem on our own computers. – Kevin Workman Jul 12 '17 at 16:16

3 Answers3

2

The behaviour you get it's totally normal.

Since I guess you are trying to print the Object returned by get, and since you have not provided an Override for the Object's toString() method, the best Java can do is to print the so called identity hashcode - "kinda of the memory address" of it.

Try adding the following as a member of your class:

         @Override
        public String toString() {
            return x+" "+y;
        }

This way then you try to print your class, Java will automatically call the provided toString()

  • The problem here is not in the way you access an element of an ArrayList, the get method all you need to do it.
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
1

You're getting that odd string because its returning the memory address of the data instead of the data itself because java is implicitly calling a toString().

Try:

yourObject x = list.get(i);

or

int x = list.get(i).xValue; / int y = list.get(i).yValue;

or just override the toString() completely by writing your own

ja08prat
  • 154
  • 10
0

Not sure if this is what you're asking, but if you have a list of Objects you can get values you are looking for with a getter method in your Object class

public class Obj {

     private int x;
     private int y;

     // constructor in which x, y values are given 
     public Obj(int x_val, int y_val) {
          this.x = x_val;
          this.y = y_val;
     }

     // getter
     public int get_x() {
          return this.x;
     }

     public int get_y() {
          return this.y;
     }



 public static void main(String[] args) {

      List<Obj> Obj_Lst = new ArrayList<Obj>();

      // adding objects to list
      Obj_Lst.add(new Obj(1,6));
      Obj_Lst.add(new Obj(2,5));
      Obj_Lst.add(new Obj(3,4));

      // getting values from object
      System.out.println(Obj_Lst.get(0).get_x());

 }

}

Output

1

T. H.
  • 1
  • 2