-3

Struggling to figure out how to access private attributes outside of a class in Java, using comparator. I'm using some code online as reference. If you change the private to public it works, but I need to know how to make it work with the variables set as private.

// Java program to demonstrate working of Comparator 
// interface 
import java.util.*; 
import java.lang.*; 
import java.io.*; 

// A class to represent a student. 
class Student 
{ 
    private int rollno; 
    private String name, address; 

    // Constructor 
    public Student(int rollno, String name, 
                            String address) 
    { 
        this.rollno = rollno; 
        this.name = name; 
        this.address = address; 
    } 

    // Used to print student details in main() 
    public String toString() 
    { 
        return this.rollno + " " + this.name + 
                        " " + this.address; 
    } 
} 

class Sortbyroll implements Comparator<Student> 
{ 
    // Used for sorting in ascending order of 
    // roll number 
    public int compare(Student a, Student b) 
    { 
        return a.rollno - b.rollno; 
    } 
} 

// Driver class 
class Main 
{ 
    public static void main (String[] args) 
    { 
        Student [] arr = {new Student(111, "bbbb", "london"), 
                        new Student(131, "aaaa", "nyc"), 
                        new Student(121, "cccc", "jaipur")}; 

        System.out.println("Unsorted"); 
        for (int i=0; i<arr.length; i++) 
            System.out.println(arr[i]); 

        Arrays.sort(arr, new Sortbyroll()); 

        System.out.println("\nSorted by rollno"); 
        for (int i=0; i<arr.length; i++) 
            System.out.println(arr[i]); 
    } 
} 
Kai
  • 47
  • 7
  • 3
    Does this answer your question? [How to sort a list by a private field?](https://stackoverflow.com/questions/52149721/how-to-sort-a-list-by-a-private-field) – Savior Apr 21 '20 at 01:51
  • thanks, i'll look through that and i'll see if it does! – Kai Apr 21 '20 at 01:52
  • I wasn't able to utilize that webpage. Couldn't properly understand how to add it to this code. – Kai Apr 21 '20 at 03:38
  • Solution 3 in the accepted answer there is probably your best bet. – Savior Apr 21 '20 at 03:41

1 Answers1

1

You should create a public getter method that returns the private field value.

public int getRollno(){return this.rollno;}

And use it to access the field from outside

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
josev.junior
  • 409
  • 2
  • 5
  • 13