1

Let's say i created an object

class Data{

        int key;
        int frec;
        int id;

        public Data(int key, int frec, int id){
            this.key = key;
            this.frec = frec;
            this.id = id;
        }
    }

and then i created a list

  List<Data> list = new ArrayList<>();
  list.add(new Data(2,3,0));

    System.out.println(list);

How to print the whole thing without this [com.company.Main$1Data@3feba861]? or better yet, how to for instance, only print out the frec? or id? and so on. I couldnt find anything on google specifically about this, an object that contains 3 integers, and how to print / point one of the value of that object.

Murokoh
  • 25
  • 5
  • 2
    Override `toString()` method with your desired behavior. – PM 77-1 Dec 10 '19 at 18:07
  • But how to do it with the int type?? i tried with overriding toString() method and it doesnt work, im assuming because different type? – Murokoh Dec 10 '19 at 18:09
  • @azurefrog i went there and tried exactly that, it didnt work, plus i have another extra question as well. as to how to use pointer in my list, to point just one of three variable in my object. – Murokoh Dec 10 '19 at 18:14
  • If done correctly it works. Obviously you are making a mistake. Since you do not show us your `toString()` method it's impossible to help you. – PM 77-1 Dec 10 '19 at 18:16
  • @PM77-1 yeap! i had no understanding in how to modify the toString method! – Murokoh Dec 11 '19 at 00:24

2 Answers2

3

You can modify your Data class to include a toString() method, like this:

public String toString() {
    return key + ", " + frec + ", " + id;
}

With that (or something similar to it), you could then do this:

Data data = new Data(1, 2, 3);
System.out.println(data);

and print output like this:

1, 2, 3
Kaan
  • 5,434
  • 3
  • 19
  • 41
0

It can be achieved by overriding the toString() method of the Object class.

Pratyush
  • 68
  • 8