0
package basicprograms;

public class Progrm {
    public long[] ph;
    public Progrm(long[] ph){
        this.ph=ph;
    }
}

The main method:

package basicprograms;

import java.util.ArrayList;

public class UseProgrm {
    public static void main(String[] args) {
        ArrayList<Progrm> ar = new ArrayList<>();
        Progrm p1 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
        Progrm p2 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
        Progrm p3 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
        ar.add(p1);
        ar.add(p2);
        ar.add(p3);
        for (int i = 0; i < ar.size(); i++) {
            System.out.println(ar.get(i));
        }
    }
}
Elletlar
  • 3,136
  • 7
  • 32
  • 38

3 Answers3

2

By default, all classes in Java inherit from the Object class. In this case what you are actually printing is Progrm::toString method that is inherited for the Object class and by default is returning the hash. If you would like to print the content of the array(public member ph of the Progrm class) then you should override the toString of Progrm as follows:

public class Progrm {

    public long[] ph;

    public Progrm(long[] ph) {
        this.ph=ph;
    }

    @Override
    public String toString() {
        return "Progrm{" +
            "ph=" + Arrays.toString(ph) +
            '}';
    }
}

and the output will be:

Progrm{ph=[942758427, 4298578432, 3425962]} 
Progrm{ph=[942758427, 4298578432, 3425962]}
Progrm{ph=[942758427, 4298578432, 3425962]}

For more info on Object::toString, you can refer to : Why does the default Object.toString() include the hashcode?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dbl
  • 1,109
  • 9
  • 17
0

You have to override the toString() method in your Program class

now, the System.out.println statements are calling the default implementation of the Object class.

Add this to your Program class:

public String toString() {
  StringBuilder b = new StringBuilder("");
  for ( long p : ph) {
    b.append("Value: " + p + ", ");
  }
  return b.toString();
}

Afterwards, you can modify it to fit your needs.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
0

Try this:

for (int i = 0; i < ar.size(); i++) {
     for(int j = 0; j < ar.get(i).ph.length; j++)
          System.out.println(ar.get(i).ph[j]);
 }
Cedric
  • 19
  • 6