0

So I have a generic class that I've created and I need to print it out to see if I am passing the correct values. Only when I print it I get

 PointList@7852e922

I don't understand how I can print out the actual values. Everything I've read just helps with ArrayLists and not generic classes. I tried using stringbuilder and I tried writing a toString method in my PointList class and I keep getting errors. Am I on the right track using one of those two methods? Is there a way to print it out?

public class PointListTest{

public static void main(String[] args){

//create point ints
Point<Integer> pointOne = new Point<Integer>(1,2);
Point<Integer> pointTwo = new Point<Integer>(3,4);
Point<Integer> pointThree = new Point<Integer>(5,6);

//make object PointList pointlist for int
PointList<Point<Integer>> newPointList = new PointList<Point<Integer>>();


//add points to list
newPointList.add(pointOne);
newPointList.add(pointTwo);
newPointList.add(pointThree);

//print list
System.out.println(newPointList);

Here is the PointList class

public class PointList<E>{

private List<E> myList;

E data;

public PointList(E obj){

myList = new ArrayList<>();

data = obj;

}//end constructor 

public PointList(){

myList = new ArrayList<>();

}//end no args constructor
public void add(E obj) {


  myList.add(obj);
 }

This is what I have in my toString method.

   @Override
   public String toString(){

    return("" + data);

}//end toString

Point class has this toString method

@Override
 public String toString(){
   return (xCordinate + "," + yCordinate);
}//end toString
Dan Erv
  • 5
  • 3

2 Answers2

2

Try defining a custom toString method in your class PointList, Assuming the Point has its own toString defined, the below code should work

 @Override
 public String toString(){
     String str = this.myList != null ? this.myList.stream().map(Object::toString).collect(Collectors.joining(", ")) : "";
     return str;
 }
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
0

When you print a class directly, Java actually calls the class's toString() method. This defaults to printing some pretty unhelpful information (which is what you're seeing in PointList@7852e922.

If you want more meaningful information printed by your class, you need to override the toString() method and provide your own:

@Override
public String toString() {
    return "Name = " + name;
}

Obviously, you'd adjust the returned value to suit your own needs.

Zephyr
  • 9,885
  • 4
  • 28
  • 63
  • When I tried writing a toString method I kept getting a null value. Does this mean there is an issue with how I am implementing it? – Dan Erv Feb 19 '19 at 05:18
  • I would suspect so, yes. If the value you're returning is `null` when the `toString()` method is called, I would expect a `null` result. – Zephyr Feb 19 '19 at 05:19
  • Alright thank you. Then I was using toString() correctly. – Dan Erv Feb 19 '19 at 05:22