Docsity

Arrays of Objects in Java: A Practical Guide with Examples, Lecture notes of Java Programming

Toggle sidebar
bg1
Arrays of Objects
Parallel array solution:
rollNum= {6016, 6024, 6078};
midsemMarks = {61.7, 54 , 74.2 };
name = {"Abhishek Murthy", "Abhishek Singh",
"Ankit"};
In practice, parallel arrays are hard to maintain.
Better: define class STUDENT with attributes
- rollNum,
- marks,
- name,
and define arrays of the STUDENT object: Student[ ]
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Arrays of Objects in Java: A Practical Guide with Examples and more Lecture notes Java Programming in PDF only on Docsity!

Arrays of Objects

Parallel array solution:

rollNum= {6016, 6024, 6078};

midsemMarks = {61.7, 54 , 74.2 };

name = {"Abhishek Murthy", "Abhishek Singh",

"Ankit"};

In practice, parallel arrays are hard to maintain.

Better: define class STUDENT with attributes

  • rollNum,
  • marks,
  • name,

and define arrays of the STUDENT object: Student[ ]

Also, may need to return more than one parameter

  • Want to identify both maximum marks, and also who has this maximum marks - Need to return two values from FindMax - Or return index and find each record
  • Better: use Student as object

Other Classes used by “Student” Note: private Date birthDate; Requires class “Date”. This is defined in separate file Date.java in the same directory. Similarly private Course[] courseList; Requires the class “Course”, defined in Course.java. These three files constitute a “package”. If they are in the same directory, Java automatically recognizes them as a package Please save these files to the same directory and test: Student.java Course.java Date.java

Student Class: Constructors // Default constructor public Student() { // initialise instance variables birthDate = new Date(); courseList = new Course[MAX_COURSES]; } /** Constructor with roll number */ public Student(String roll) { rollNum = roll; birthDate = new Date(); courseList = new Course[MAX_COURSES]; }

Multidimensional Arrays

int[][] sqr = new int[5][5];

// this prints out the array

for (int r=0; r < sqr.length; r++) {

System.out.println(Arrays.toString( sqr[r]));

Note: Array elements get default values. E.g. numericals get zero. Can also initialize multidim arrays: int [] [] magicSquare = { {8, 1, 6} , {3, 5, 7}, {4, 9, 2} };

Non-uniform rows Arrays

int[][] tri;

tri = new int[5][];

for (int r=0; r < tri.length; r++)

tri[r] = new int[r+1];

// Allocate each row with differing size

for (int r=0; r<tri.length; r++)

System.out.println(Arrays.toString(tri[r]));