National University of San Agustin
System Engineer School
EDAT - Lab 02 - Generics and Arrays
Christian E. Portugal-Zambrano
April 23, 2019
1 Introduction
Java Generic methods 1 and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively 2 Generics also provide compile-time type safety that allows
programmers to catch invalid types at compile time. Using Java Generic concept, we
might write a generic method for sorting an array of objects, then invoke the generic
method with Integer arrays, Double arrays, String arrays and so on, to sort the array
elements. You can write a single generic method declaration that can be called with
arguments of dierent types. Based on the types of the arguments passed to the generic
method, the compiler handles each method call appropriately. Following are the rules to
dene Generic Methods:
• All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next
example).
• Each type parameter section contains one or more type parameters separated by
commas. A type parameter, also known as a type variable, is an identier that
species a generic type name.
1
You can see the java documentation about generics on Java documentation
2
All the information about this introduction was taken from Tutorial points, you can visit that place
for more information or examples.
1
• The type parameters can be used to declare the return type and act as placeholders
for the types of the arguments passed to the generic method, which are known as
actual type arguments.
• A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double
and char).
2 Objectives
• Get advanced knowledge about arrays and they use as fundamentals data struc-
tures.
• Implement a Mat class that let introduce some matrix concepts.
• Get improved experience about the use of arrays and generics.
3 Pre-requisites
We must require a basic use of arrays 1D, 2D and more, additionally we must have
theoretical concepts about generics, its use and limitations, some linear algebra concepts
are necessary too.
4 Algorithms and code presentation
So, as we are working with LATEX algorithms presentation will be easy, you just need to
add this at the header of your document:
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage[noend]{algpseudocode}
Also if you need to add some code you can use:
\usepackage{listings}
\usepackage{color}
\lstset{frame=tb,
language=Java,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{gray},
2
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}
More information about Listing on https://en.wikibooks.org/wiki/LaTeX/Source_
Code_Listings
5 The Printer class
In this practice we will be implementing a Mat class that we can use as a Matrix repre-
sentation, as a Matrix this class must perform some operations as sum, multiplication,
division, substraction, transpose, ones, zeros, diagonal and dot multiplication. Accom-
panying this practice there is a Mat.java and a Printer.java les that we explain next:
public class Printer{
public <T> void print(Mat<T> _mat){
for (int i=0; i<_mat.rows(); i++){
System.out.print("|");
for (int j=0; j<_mat.cols(); j++){
System.out.print(_mat.at(i,j));
if(j != _mat.cols()-1) System.out.print("\t");
}
System.out.println("|");
}
}
}
This Printer class is used to print a representation of the matrix, you can use square and
non-square matrix, for this practice you don't have to write any code to this class, but
you must use it into your Mat class. As a rst task you have to compile and run the
Printer and Mat class given, you must test with another values and print them. Then
ask these question, is really necessary to use Generics in the printer class?, until now
what is the use of generics in java?
6 The Mat Class
This class is a representation of a matrix, so we can perform some matrix operations, the
implementation is described as:
We use an array of Object types to manipulate the matrix data, the only condition to
this class is that the data must be stored into a one dimensional array but the operation
can be two dimensional or n-dimensional. cols and rows stores information about the
rows and cols of the matrix, you matrix must works with square and non-square matrix.
3
public class Mat<T>{
private Object[] data;
private int cols;
private int rows;
There are two types of constructors, one is to create a square matrix of three by three
with default values of zero.
public Mat() {
data = new Object[3];
for (int i=0; i<3; i++) {
data[i] = 0;
}
rows =3;
cols =3;
}
and the other constructor lets you choose the rows and cols of the matrix. Note that these
operation are with one dimensional arrays but the matrix operations must be considered
as 2d dimensional matrix.
public Mat(T [] _data, int _rows, int _cols) {
data = new Object[_data.length];
for (int i=0; i< _data.length; i++){
data[i] = _data[i];
}
rows = _rows;
cols = _cols;
}
7 To Do
At this time we need to make our Mat class usable to perform some linear algebra math,
for this task we need to implement some basic methods, your work is implement these
methods as described below, but before do this take a look into the at method, do you
see some relation between the one dimensional array and a two dimensional array?
@SuppressWarnings("unchecked")
public T at(int _r, int _c) {
return (T)data[_r*cols+_c];
}
For this code what does mean the @suppressWarning used in the code? It is really
necessary? is there another way to make this code without the @supressWarning?
4
Sum of matrix This is accomplished with two matrices of the same size, you must
sure that only sum of matrices of the same size are performed, the method is dened as:
public Mat<T> sum(Mat<T> _mat) {
return new Mat<T>();
}
and you must return a resulting Mat of the sum, then you must implement the same
but using an scalar, remember that the sum of a scalar is in a element-wise form, so the
scalar is added to each one of the matrix elements.
public Mat<T> sum(T _scalar) {
return new Mat<T>();
}
Multiplication of matrices There are two ways of perform multiplications, the
rst one is an element-wise multiplication, is the same as the sum-wise but this time you
have to multiply the elements.
public Mat<T> mult(Mat<T> _mat) {
return new Mat<T>();
}
and the scalar multiplications must be implemented too.
public Mat<T> mult(int _scalar) {
return new Mat<T>();
}
For the next operation you must think about the relation between an one dimensional
and a two dimensional array, because the dot multiplication is when you perform the
multiplication of the rst row of the left matrix with the rst column of the right matrix
and so on, don't forget that the index of rows from the right matrix must be the same
as the columns of the left matrix, e.g (2,3)dot(3.2) = (2,2) matrix.
public Mat<T> dot(Mat<T> _mat) {
return new Mat<T>();
}
Transpose of a matrix Remember that the transpose of a matrix is when each row
is passed as column, e.g
2 3 4 2 1 5
1 34 36 → 3 34 12
5 12 9 4 36 9
The code is:
5
public Mat<T> t(){
return new Mat<T>();
}
Finally, you have to implement the methods ones and zeros that constructs Mat objects
with ones or zeros of customized size. As a major restriction you must observe the
initialization of the matrices and you must not use any other java class as ArrayList or
similars.
public static <T> void main(String [] args){
Printer printer = new Printer();
Mat<Integer> A = new Mat<Integer>(new
Integer[]{100,23,3444,455,52,611},2,3);
Mat<Float> B = new Mat<Float>(new Float[]{4.3f,5.4f,6.56f,7.21f},2,2);
Mat<Double> C = new Mat<Double>(new
Double[]{1.23,3.145,2.33,4.3,45.6,466.4,56.5,4.3,7.6},3,3);
printer.print(A);
printer.print(B);
printer.print(C);
/* your code here showing the operations of
* sum, mult, dot and transpose
*/
}
8 Deadline
For this practice one score will be taken at class time and nal results presented in the
next class. Remember that plagiarism must be avoided and if it is detected the grade
will be zero and repetition informed to superior authorities. A pdf with you CUI must
be presented at the next class, this pdf must be a report about your implementation and
results, you can use the TEX model from here All question and doubts must be done to
email.