-5

i want to print element from arraylist, but i'm getting wrong output (.A@15db9742)

import java.util.ArrayList;
class A {
int aa;
A(int x) { 
    aa=x;
}   
}
public class test{
public static void main(String[] args){
    A aa = new A(1);
    A ab = new A(2);
    A ac = new A(3);
ArrayList<A> lista = new ArrayList<A>(3);
lista.add(aa);
lista.add(ab);
lista.add(ac);
System.out.println(lista.get(0)); }
bardamu
  • 57
  • 2
  • 8

2 Answers2

2

Assuming your code is supposed to return 1, your issue lies in that your class A doesn't include a toString method

heres some info on toString: toString

insert this method into class A:

public String toString() {
    return Integer.toString(aa);
}

for future reference, try to style your code slightly more clearly so that others could read what you're trying to do

ex:

import java.util.ArrayList;

class A {
    int aa;

    A(int x) {
        aa=x;
    }
}

public class test {
    public static void main(String[] args) {
        A aa = new A(1);
        A ab = new A(2);
        A ac = new A(3);
        ArrayList<A> lista = new ArrayList<A>(3);
        lista.add(aa);
        lista.add(ab);
        lista.add(ac);
        System.out.println(lista.get(0));
    }
}

good luck :D

0xDECAFC0FFEE
  • 370
  • 1
  • 5
0

You must override toString method in class A:

public String toString() { 
return "aa: " + this.aa;
} 
Krishnanunni P V
  • 689
  • 5
  • 18
  • 32