Multidimensional data, writing files
and object equality
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
May 26, 2025
equals
, which can be used to check if two objects of the same type have the same contents or state.int
is 0.int rows = 2;
int columns = 3;
int[][] twoDimensionalArray = new int[rows][columns];
System.out.println("row, column, value");
for (int row = 0; row < twoDimensionalArray.length; row++) {
for (int column = 0; column < twoDimensionalArray[row].length; column++) {
int value = twoDimensionalArray[row][column];
System.out.println("" + row + ", " + column + ", " + value);
}
}
int rows = 2;
int columns = 3;
int[][] twoDimensionalArray = new int[rows][columns];
twoDimensionalArray[0][1] = 4;
twoDimensionalArray[1][1] = 1;
twoDimensionalArray[1][0] = 8;
System.out.println("row, column, value");
for (int row = 0; row < twoDimensionalArray.length; row++) {
for (int column = 0; column < twoDimensionalArray[row].length; column++) {
int value = twoDimensionalArray[row][column];
System.out.println("" + row + ", " + column + ", " + value);
}
}
ArrayList<ArrayList<Integer>>
.ArrayList<ArrayList<Integer>>
:ArrayList<ArrayList<Integer>> matrix = new ArrayList<>();
int rows = 2;
int columns = 3;
// initialize matrix with 0s
for (int i = 0; i < rows; i++) {
ArrayList<Integer> row = new ArrayList<>();
for (int j = 0; j < columns; j++) {
row.add(0);
}
matrix.add(row);
}
// set some values
matrix.get(0).set(1, 4);
matrix.get(1).set(1, 1);
matrix.get(1).set(0, 8);
// print matrix
System.out.println("row, column, value");
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix.get(i).size(); j++) {
System.out.println(i + ", " + j + ", " + matrix.get(i).get(j));
}
}
PrintWriter
class receives as its parameter a string that represents the location of the target file.PrintWriter writer = new PrintWriter("file.txt");
writer.println("Hello file!"); //writes the string "Hello file!" and line change to the file
writer.println("More text");
writer.print("And a little extra"); // writes the string "And a little extra" to the file without a line change
writer.close(); //closes the file and ensures that the written text is saved to the file
print
does not add line changes, and you have to add them yourself.println
adds a new line change at the end of the parameter string it receives.PrintWriter
class might throw an exception that must be either handled or thrown so that it is the responsibility of the calling method.public class Storer {
public void writeToFile(String fileName, String text) throws Exception {
PrintWriter writer = new PrintWriter(fileName);
writer.println(text);
writer.close();
}
}
writeToFile
method above we begin by creating a PrintWriter
object.fileName
indicates.println
method.try-catch
block or the handling responsibility has to be transferred elsewhere.writeToFile
method, the responsibility to handle the exception is placed on the method that calls writeToFile
.writeToFile
methodmain
method that calls the writeToFile
of a Storer
object.main
method to handle the exception – it, too, can state that it might throw an exception by adding throws Exception
to the method definition.public static void main(String[] args) throws Exception {
Storer storer = new Storer();
storer.writeToFile("diary.txt", "Dear diary, today was a good day.");
}
try-catch
block or throwing them out of the method.public ArrayList<String> readLines(String fileName) {
ArrayList<String> lines = new ArrayList<>();
try (Scanner scanner = new Scanner(Paths.get(fileName))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lines.add(line);
}
scanner.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
return lines;
}
throws ExceptionType
is added before the opening bracket of a method.readLines
method has to either handle the exception in a try-catch block or shift the responsibility yet forward.NullPointerException
Thrown when trying to use an object reference that is null
.
ArrayIndexOutOfBoundsException
Thrown when accessing an invalid index in an array.
ClassCastException
Thrown when trying to cast an object to an incompatible type.
NumberFormatException
Thrown when converting a badly formatted string to a number.
FileNotFoundException
Thrown when trying to access a file that does not exist.
equals
method.Scanner scanner = new Scanner(System.in);
System.out.println("Enter two words, each on its own line.")
String first = scanner.nextLine();
String second = scanner.nextLine();
if (first.equals(second)) {
System.out.println("The words were the same.");
} else {
System.out.println("The words were not the same.");
}
With primitive variables such as int
, comparing two variables can be done with two equality signs.
This is because the value of a primitive variable is stored directly in the “variable’s box”.
The value of reference variables, in contrast, is an address of the object that is referenced; so the “box” contains a reference to the memory location.
Using two equality signs compares the equality of the values stored in the “boxes of the variables” – with reference variables, such comparisons would examine the equality of the memory references.
The method equals
is similar to the method toString
in the respect that it is available for use even if it has not been defined in the class.
The default implementation of this method compares the equality of the references.
equals
methodSimpleDate
class.SimpleDate first = new SimpleDate(1, 1, 2000);
SimpleDate second = new SimpleDate(1, 1, 2000);
SimpleDate third = new SimpleDate(12, 12, 2012);
SimpleDate fourth = first;
if (first.equals(first)) {
System.out.println("Variables first and first are equal");
} else {
System.out.println("Variables first and first are not equal");
}
if (first.equals(second)) {
System.out.println("Variables first and second are equal");
} else {
System.out.println("Variables first and second are not equal");
}
if (first.equals(third)) {
System.out.println("Variables first and third are equal");
} else {
System.out.println("Variables first and third are not equal");
}
if (first.equals(fourth)) {
System.out.println("Variables first and fourth are equal");
} else {
System.out.println("Variables first and fourth are not equal");
}
public class SimpleDate {
private int day;
private int month;
private int year;
public SimpleDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return this.day;
}
public int getMonth() {
return this.month;
}
public int getYear() {
return this.year;
}
@Override
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
}
There is a problem with the previous program.
Even though two dates (first and second) have exactly the same values for object variables, they are different from each other from the point of view of the default equals
method.
If we want to be able to compare two objects of our own design with the equals
method, that method must be defined in the class.
The method equals
is defined as a method that returns a boolean type value – the return value indicates whether the objects are equal.
The equals
method is implemented in such a way that it can be used to compare the current object with any other object.
equals
method for a classObject
-type object as its single parameter – all objects are Object
-type, in addition to their own type.equals
method first compares if the addresses are equal: if so, the objects are equal.Object
-type object passed as the parameter is converted to the type of the object that is being examined by using a type cast, so that the values of the object variables can be compared.SimpleDate
equals
methodpublic class SimpleDate {
private int day;
private int month;
private int year;
public SimpleDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return this.day;
}
public int getMonth() {
return this.month;
}
public int getYear() {
return this.year;
}
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
// if the type of the compared object is not SimpleDate, the objects are not equal
if (!(compared instanceof SimpleDate)) {
return false;
}
// convert the Object type compared object
// into a SimpleDate type object called comparedSimpleDate
SimpleDate comparedSimpleDate = (SimpleDate) compared;
// if the values of the object variables are the same, the objects are equal
if (this.day == comparedSimpleDate.day &&
this.month == comparedSimpleDate.month &&
this.year == comparedSimpleDate.year) {
return true;
}
// otherwise the objects are not equal
return false;
}
@Override
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
}
Person
objects too.Person
objects that don’t have a separate SimpleDate object.equals
method for comparing them.Person
equals
methodpublic class Person {
private String name;
private int age;
private int weight;
private int height;
// constructors and methods
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
// if the compared object is not of type Person, the objects are not equal
if (!(compared instanceof Person)) {
return false;
}
// convert the object into a Person object
Person comparedPerson = (Person) compared;
// if the values of the object variables are equal, the objects are equal
if (this.name.equals(comparedPerson.name) &&
this.age == comparedPerson.age &&
this.weight == comparedPerson.weight &&
this.height == comparedPerson.height) {
return true;
}
// otherwise the objects are not equal
return false;
}
// .. methods
}
equals
method is used with lists.Bird
without any equals
method.ArrayList<Bird> birds = new ArrayList<>()
Bird red = new Bird("Red");
if (birds.contains(red)) {
System.out.println("Red is on the list.");
} else {
System.out.println("Red is not on the list.");
}
birds.add(red);
if (birds.contains(red)) {
System.out.println("Red is on the list.");
} else {
System.out.println("Red is not on the list.");
}
System.out.println("However!");
red = new Bird("Red");
if (birds.contains(red)) {
System.out.println("Red is on the list.");
} else {
System.out.println("Red is not on the list.");
}
We can notice in the previous example that we can search a list for our own objects.
First, when the bird had not been added to the list, it is not found – and after adding it is found.
When the program switches the red
object into a new object, with exactly the same contents as before, it is no longer equal to the object on the list, and therefore cannot be found on the list.
The contains
method of a list uses the equals
method that is defined for the objects in its search for objects.
In the example above, the Bird
class has no definition for that method, so a bird with exactly the same contents – but a different reference – cannot be found on the list.
equals
mehtod for the bird classequals
method for the class Bird
.public class Bird {
private String name;
public Bird(String name) {
this.name = name;
}
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
// if the compared object is not of type Bird, the objects are not equal
if (!(compared instanceof Bird)) {
return false;
}
// convert the object to a Bird object
Bird comparedBird = (Bird) compared;
// if the values of the object variables are equal, the objects are, too
return this.name.equals(comparedBird.name);
/*
// the comparison of names above is equal to
// the following code
if (this.name.equals(comparedBird.name)) {
return true;
}
// otherwise the objects are not equal
return false;
*/
}
}
Bird
objects can be comparedArrayList<Bird> birds = new ArrayList<>()
Bird red = new Bird("Red");
if (birds.contains(red)) {
System.out.println("Red is on the list.");
} else {
System.out.println("Red is not on the list.");
}
birds.add(red);
if (birds.contains(red)) {
System.out.println("Red is on the list.");
} else {
System.out.println("Red is not on the list.");
}
System.out.println("However!");
red = new Bird("Red");
if (birds.contains(red)) {
System.out.println("Red is on the list.");
} else {
System.out.println("Red is not on the list.");
}
equals
, which can be used to check if two objects of the same type have the same contents or state.Computer Language