i'm doing heapSort algorithm. where I have to creat an array of reference to object. I actually creaed array which is empty so println displays null. thats fine. but when I actually add object(each listing object contain information of student-their name, id#, and gpa) and try to print it, it gives me result. My problem is I want to use toString method coded in Listing class(student information) to print all information. But it gives me all information when I directly give array element to print statement. I think this would no longer keep my code encapsulated.
System. out.println(data[j]); & System.out.println(data[j].toString); this both gives me same output.
I dont know whether it is correct or wrong. I would be grateful if anyone can explain me difference between both eprint statements and how encapsulation will work here. I'm also including code that I've tried.
import java.util.Scanner;
public class MainHeapSort {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students: ");
int size = input.nextInt();
Listing[] data = new Listing[size];// data of class listing that stores students information
//following two statements says that data array is empty hence prints null
//for(int j = 0; j < size; j++){
//System.out.println(data[j]);}
Listing temp = new Listing("","","");
for(int j = 0; j < data.length ; j++){
System.out.println("Enter name of the student: ");
String stuName = input.next();
System.out.println("Enter student ID number: ");
String idNumber = input.next();
System.out.println("Enter students GPA: ");
String stuGpa = input.next();
Listing student = new Listing(stuName, idNumber, stuGpa);
data[j] = student.deepCopy();
}
// this is swap just for my understanding.
temp = data[0];
data[0] = data[2];
data[2] = data[1];
data[1] = temp;
for(int j = 0; j < size; j++){
System.out.println(data[j]);
System.out.println("after changing index: ");
System.out.println(data[j].toString(…
}
}
}
here is the code for class Listing that stores student's info
public class Listing
{ private String name; // key field
private String address;
private String number;
public Listing(){}
public Listing(String n, String a, String num )
{ name = n;
address = a;
number = num;
}
public String toString( )
{ return("Name is " + name +
"\nAddress is " + address +
"\nNumber is " + number + "\n");
}
public Listing deepCopy( )
{ Listing clone = new Listing(name, address, number);
return clone;
}
public int compareTo(String targetKey)
{ return(name.compareTo(targetKey));
}
public void setAddress(String a) // coded to demonstrate encapsulation
{ address = a;
}
public String getKey()
{ return name;
}
}// end of class Listing
when I used Listing[] data array in other coding I used it as private. I dont know but I'm not able to use it as private in main method. it gives me an error.
if any body can help me understand this I would be really greatful.
Thank you