Collection Revisited
This chapter is specially designed to know what all there is in Collection at very advanced level and how it is used in the industry and in business projects. In this chapter you we will explore the following:
- What is introduced in jdk 1.5, 1.6 and 1.7?
- How does the compiler treat Collection framework in advanced versions of Java?
ArrayList
- Size means the number of elements present in ArrayList
- Capacity means the capability to store elements but in Java it is not restricted,
When we write
by default, the capacity is 10ArrayList al=new ArrayList();
This you can see in source code of ArrayList.class.See the code below from sun microsystem:
/* * Constructs an empty list with an initial capacity of 10 */ public ArrayList() { this(10); }- So, we can specify our own capacity as well
- ArrayList al=new ArrayList(6);
- But remember, this does not mean it only takes six elements
- To add primitives in ArrayList of jdk 1.4 we have add method which asks for the Object
Example
package com.javabykiran.Collection.revisited;
import java.util.ArrayList ;
/*
* @author Java By Kiran
*/
public class ArrayListTest {
public static void main(String[] args){
ArrayList arrayList = new ArrayList();
//Below is not an error as we put object type
arrayList.add(String.valueOf(34));
}
}
- Here, in this case, we must change primitive to Wrapper class as given below. For more details read the previous collection chapter.
//Below is not an error as we put Object typearrayList.add (String.valueOf (34));
OR
arrayList.add (new Integer (34));
JDK 1.5
Following are concepts introduced in new version jdk 1.5:
- Generics
- Auto Boxing
- Enhance for loop or for each loop
Generics
We use generics for type safety, which means only one type of element will get added
It does not means Sun Microsystem has changed the add method of class ArrayList
It is same as before and only changes done are in the compiler. In this case, the compiler will do more work on your behalf
One of compiler tasks, besides compilation, is addition of extra code
Declaring ArrayList in 1.5
ArrayList al = new ArrayList (); This means that the compiler will start giving errors if we try to put any elements other than an integer.
Point to be remembered: If we look at the byte code, these angular brackets are not considered. This is just for the compiler to give errors.
In these <>, classes under Object hierarchy are allowed not primitives
-
In both sides, the class type must be same, No superclass or subclass combination is allowed.
ArrayList
Like belowIn jdk 1.7 right side or is not needed ArrayList al = new ArrayList<>();
Adding elements in jdk 1.5
al.add (33)- after the above declaration, we are able to directly add 33 primitive and there is no need of typecasting. This is one of the advantages of genericsCompiler will convert this line on the fly to
al.add(new Integer(33))
Retrieving elements in jdk 1.5
al.get(index)in this case, in the earlier versions we must follow these three :Object obj=al.get (5) Integer i = (Integer) obj; int val=i.intValue ();int val = al.get (index)- This is also one of the extra features of compiler. Object gets converted into the Integer. If we use the decompiler then byte code we see this in the byte code.Another way is by using iterator:
Iterator itr=al.iterator (); while (itr.hasNext()) { int element =itr.next(); [ Due to generics we return int directly] }
foreach loop
The foreach loop in java is used for traversing arrays or collection elements. It is sometimes referred to as the For In loops
- In this case we need to remember these points below:
- No increment decrement
- No size calculation
- Must use generics for iterating
ArrayList al=new ArrayList (); for (String element : al){ System.out.println (element) } - This for loop is for compiler. It always gets converted into a simple ordinary for loop
ArrayList al=new ArrayList (); for (Student stu: al) { System.out.println (stu.age); System.out.println (stu.loc); } - This way of iterating element is most commonly used in industrial projects.
Autoboxing
- Autoboxing means automatic conversion of objects
- This happens in generics; there we don't need type casting
- Do not think it is related to collection, it's just type
Object o =3;// OK in jdk 1.5 because compiler will convert it to IntegerInteger i=78;// OKint ii=90;// OK
Business Use
Consider the following requirement:
Question: One student has age and location which needs to be added in the Arraylist, and give to ten students to other department.
package com.javabykiran.Collection.revisited;
/*
* @author Java By Kiran
*/
public class Student {
int age;
String loc;
}
Answer: First we design student as below:
Example 1: Write class which prepares Students and returns from one of method.
package com.javabykiran.Collection.revisited; import java.util.ArrayList; /* * @author Java By Kiran */ public class PrepareStudent { ArrayList buildStudents() { Student student1 = new Student(); student1.age = 28; student1.loc = "Pune"; Student student2 = new Student(); student2.age = 30; student2.loc = "Nagpur"; // Students added in arraylist // remember a1 knows students’ address but not age and loc // Here we are placing addresses not actual data in ArrayList ArrayList array ListStu = new ArrayList (); arrayListStu.add(student1); arrayListStu.add (student2); return arrayListStu; } }
Now, write the class which gets students from above class's buildStudents () method and iterate over them to get students age and location.
Example 2:
package com.javabykiran.Collection.revisited; import java.util.ArrayList; /* * @author Java By Kiran */ public class RetriveStudents { void fetchStudent() { PrepareStudent prepare = new PrepareStudent (); ArrayList listStu = prepare.buildStudents(); // enhance for loop -- for each loop for (Student student : listStu) { System.out.println("students age: " + student.age); System.out.println("students location: "+ student.loc); } } }
Write client class to test our logic.
package com.javabykiran.Collection.revisited;
/*
* @author Java By Kiran
*/
public class TestStudentsOperation {
public static void main(String[] args) {
// prepare students
PrepareStudent sp=new PrepareStudent();
sp.buildStudents();
//retrieve students
RetriveStudents retrivestudents = new RetriveStudents ();
retrivestudents.fetchStudent ();
}
}
Output:
ArrayList >>[com.javabykiran.Collection.revisited.Student@182f0db,
com.javabykiran.Collection.revisited.Student@192d342]
students age : 28
students location : Pune
students age : 30
students location : Nagpur
Business Requirement
Question: One student, who has age, location and many phone numbers, needs to be added in ArrayList and given to other department which has ten students.
package com.javabykiran.Collection.revisited; import java.util.ArrayList; /* * @author Java By Kiran */ public class Student { int age; String loc; ArrayList alMobNo; } package com.javabykiran.Collection.revisited; import java.util.ArrayList; /* * @author Java By Kiran */ public class StudentPrepare { ArrayList buildStudents(){ Student student1 = new Student(); student1.age = 28; student1.loc = "Pune"; //creates list of mobile numbers of student1 ArrayList alMobNoStu1 = new ArrayList<>(); alMobNoStu1.add("8888809416"); alMobNoStu1.add("9552343698"); student1.alMobNo = alMobNoStu1; Student student2 = new Student(); student2.age = 28; student2.loc = "Pune"; //creates list of mobilenumbers of student2 ArrayList alMobNoStu2 = new ArrayList<>(); alMobNoStu2.add("8234876642"); alMobNoStu2.add("3455455441"); student2.alMobNo = alMobNoStu2; // Students added in arraylist //remember al knows students’ address not their age and loc //Here we are placing address, not actual data in ArrayList ArrayList arrayListStu = new ArrayList<>(); arrayListStu.add(student1); arrayListStu.add (student2); System.out.println("ArrayList >> "+ arrayListStu); return arrayListStu; } }
For Fetching Students use the method given below:
Example 4:
void fetchStudent() { StudentPrepare prepare = new StudentPrepare(); ArrayList listStu = prepare.buildStudents(); //Enhance for loop -- foreach loop for(Student student : listStu) { System.out.println("students age: " + student.age); System.out.println("students location: " + student.loc); ArrayList alMobNo = student.alMobNo; for (String mobNo : alMobNo) { System.out.println("al mob no" + mobNo); } // end 1st For loop }// end 2nd for loop }
Output:
ArrayList >> [com.javabykiran.Collection.revisited.Student@182f0db,
com.javabykiran.Collection.revisited.Student@192d342]
students age : 28
students location : Pune
al mob no 8888809416
al mob no 9552343698
students age : 30
students location : Nagpur
al mob no 8234876642
al mob no 3455455441
Consider the following requirement:
Example 5:
Question: One student has age, location and a phone having two types, one landline number and many mobile numbers. It needs to be added in ArrayList and given to other department which has ten students.
First we design Phone as below:
package com.javabykiran.Collection.revisited; import java.util.ArrayList; /* * @author Java By Kiran */ public class Phone { int landLineNo; ArrayList mobNos;
First we design Student as below having phone attribute: This also shows one to one relationship.
package com.javabykiran.Collection.revisited;
import java.util.ArrayList;
/*
* @author Java By Kiran
*/
public class Student {
int age;
String loc;
Phone p;
}