Professional Documents
Culture Documents
This framework is
provided in the java.util package. Objects can be stored, retrieved, and
manipulated as elements of collections. Collection is a Java Interface. Collections
can be used in various scenarios like Storing phone numbers, Employee names
database etc. They are basically used to group multiple elements into a single unit.
Some collections allow duplicate elements while others do not. Some collections are
ordered and others are not.
Collection
Set
List
SortedSet
Map
SortedMap
Concrete Classes
The concrete classes that are specific implementations of the core interfaces, providing data structures
that a java program can use.
Note: Concrete Classes for the Map is shown in the previous section.
Standard utility methods and algorithms
Below is an example program showing the storing and retrieving of a few Collection Types
import java.util.*;
Output
ArrayList Elements
[Beginner, Java, tutorial]
LinkedList Elements
[Beginner, Java, tutorial]
Set Elements
[tutorial, Beginner, Java]
Map Elements
{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}
3. Reduces the effort required to design and implement APIs by eliminating the need to
produce ad hoc collections APIs.
4. It provides useful data structures and algorithms that reduces programming effort due to
which we need not to write them ourselves.
6. Helps in establishing a common language to pass collections back and forth that provides
interoperability between unrelated APIs.
7. Collection is resizable and can grow.
Description:
Here we can see example for basic ArrayList operations like creating object for ArrayList, adding objects into ArrayList, ac
objects based on index, searching an object in ArrayList whether it is listed under this instance or not, adding elements at s
checking whether the ArrayList is empty or not, getting object index, and finally size of the ArrayList.
Code:
?
1
2
3 package com.java2novice.arraylist;
4
import java.util.ArrayList;
5
6 public class MyBasicArrayList {
7
8 public static void main(String[] a){
9
10 ArrayList<String> al = new ArrayList<String>();
11 //add elements to the ArrayList
12 al.add("JAVA");
al.add("C++");
13 al.add("PERL");
14 al.add("PHP");
15 System.out.println(al);
16 //get elements by index
System.out.println("Element at index 1: "+al.get(1));
17
System.out.println("Does list contains JAVA? "+al.contains("JAVA"));
18 //add elements at a specific index
19 al.add(2,"PLAY");
20 System.out.println(al);
21 System.out.println("Is arraylist empty? "+al.isEmpty());
System.out.println("Index of PERL is "+al.indexOf("PERL"));
22 System.out.println("Size of the arraylist is: "+al.size());
23 }
24 }
25
26
Output:
[JAVA, C++, PERL, PHP]
Element at index 1: C++
Does list contains JAVA? true
[JAVA, C++, PLAY, PERL, PHP]
Is arraylist empty? false
Index of PERL is 3
Size of the arraylist is: 5
Program: How to read all elements in ArrayList by using iter
Description:
Here we can see example for reading all elements from ArrayList by using Iterator. Also you can iterate through the ArrayL
index too.
Code:
1 package com.java2novice.arraylist;
3 import java.util.ArrayList;
import java.util.Iterator;
4
5
public class ArrayListIterator {
6
7
public static void main(String a[]){
8
ArrayList<String> arrl = new ArrayList<String>();
9
//adding elements to the end
10
arrl.add("First");
11
arrl.add("Second");
12 arrl.add("Third");
13 arrl.add("Random");
15 while(itr.hasNext()){
System.out.println(itr.next());
16
}
17
}
18
19 }
20
Output:
First
Second
Third
Random
Program: How to copy or clone a ArrayList?
Description:
Here we can see example for creating duplicate object of an ArrayList instance. we can done this by using clone() function
Code:
package com.java2novice.arraylist;
import java.util.ArrayList;
Output:
Description:
Here we can see example for copying another collection instance objects to existing ArrayList.
Code:
package com.java2novice.arraylist;
import java.util.ArrayList;
import java.util.List;
Output:
Description:
Here we can see example for deleting all objects from ArrayList at one method call. We can do this by calling clear() meth
ArrayList, it will delete all objects.
Code:
1 package com.java2novice.arraylist;
3 import java.util.ArrayList;
4
public class ClearMyArrayList {
5
6
public static void main(String a[]){
7
ArrayList<String> arrl = new ArrayList<String>();
8
//adding elements to the end
9
arrl.add("First");
10
arrl.add("Second");
11
arrl.add("Third");
12 arrl.add("Random");
13 System.out.println("Actual ArrayList:"+arrl);
14 arrl.clear();
}
16
}
17
18
Output:
Description:
Here we can see example for finding whether the instance of an ArrayList contains all objects of another Collection instanc
checking with another List instance.
Code:
1 package com.java2novice.arraylist;
3 import java.util.ArrayList;
import java.util.List;
4
5
public class MyElementCheck {
6
7
public static void main(String a[]){
8
ArrayList<String> arrl = new ArrayList<String>();
9
arrl.add("First");
10
arrl.add("Second");
11
arrl.add("Third");
12 arrl.add("Random");
15 list.add("Second");
list.add("Random");
16
System.out.println("Does ArrayList contains all list elements?: "
17
+arrl.containsAll(list));
18
list.add("one");
19
System.out.println("Does ArrayList contains all list elements?: "
20
+arrl.containsAll(list));
21 }
22 }
23
Output:
Output:
Type: java.lang.String
Type: java.lang.Boolean
Program: Write a simple generics class example with two ty
parameters.
Below example shows how to create a simple generics class with two type parameters. Look at the class
defined two types of parameters called U & V, seperated by ",". You can define multiple type parameter
",". Look at sample code for more comments.
package com.java2novice.generics;
/**
* Simple generics class with two type parameters U, V.
*/
class SimpleGen<U, V>{
Output:
U Type: java.lang.String
V Type: java.lang.Integer
Program: How implement bounded types (extend superclass
generics?
As of now we have seen examples for only one type parameter. What happens in case we want to access
objects comes from same family, means extending same super class? You can restrict the generics type p
certain group of objects which extends same super class. You can achieve this my specifying extends <su
class definitions, look at the example, it gives you more comments to understand.
package com.java2novice.generics;
1
2
public class MyBoundedClassEx {
3
4
public static void main(String a[]){
5
//Creating object of sub class C and
6
//passing it to BoundEx as a type parameter.
7
BoundEx<C> bec = new BoundEx<C>(new C());
8 bec.doRunTest();
beb.doRunTest();
12
//similarly passing super class A
13
BoundEx<A> bea = new BoundEx<A>(new A());
14
bea.doRunTest();
15
//If you uncomment below code it will throw compiler error
16
//becasue we restricted to only of type A and its sub classes.
17
//BoundEx<String> bes = new BoundEx<String>(new String());
class MyClass<T extends TestClass & TestInterface> {
1 package com.java2novice.generics;
17 //bea.doRunTest();
18 }
}
19
20
class BoundExmp<T extends X>{
21
Program: What is generics wildcard arguments? Give an exa
Below example exmplains what is wildcard arguments and how it helps us to solve problem. In the exam
two classes called CompAEmp and CompBEmp extending Emp class. We have a generic class called MyEm
where we have utilities to perform employee functions irrespective of which comapany emp belogns too
accepts subclasses of Emp. Incase if we want to compare salaries of two employees, how can we do usin
MyEmployeeUtil class? U can think that below sample code might work, but it wont work.
if(emp.getSalary() == otherEmp.getSalary()){
return true;
}
return false;
}
Because once you create an object of MyEmployeeUtil class, the type argument will be specific to an ins
you can compare between only same object types, ie, you can comapare either objects of CompAEmp or
but not between CompAEmp and CompBEmp. To solve this problem, wildcard argument will helps you. L
sample code, which can solve your problem.
if(emp.getSalary() == otherEmp.getSalary()){
return true;
}
return false;
}
So "?" will solve the issue. Look below for complete example.
package com.java2novice.generics;
private T emp;
if(emp.getSalary() == otherEmp.getSalary()){
return true;
}
return false;
}
class Emp{
Output:
public JPanels() {
super("Using JPanels with Borders");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.lightGray);
JPanel controlArea = new JPanel(new GridLayout(3, 1));
String[] colors = { "Red", "Green", "Blue",
"Black", "White", "Gray" };
controlArea.add(new SixChoicePanel("Color", colors));
String[] thicknesses = { "1", "2", "3", "4", "5", "6" };
controlArea.add(new SixChoicePanel("Line Thickness",
thicknesses));
String[] fontSizes = { "10", "12", "14", "18", "24", "36" };
controlArea.add(new SixChoicePanel("Font Size",
fontSizes));
content.add(controlArea, BorderLayout.EAST);
JPanel drawingArea = new JPanel();
// Preferred height is irrelevant, since using WEST region
drawingArea.setPreferredSize(new Dimension(400, 0));
drawingArea.setBorder
(BorderFactory.createLineBorder (Color.blue, 2));
drawingArea.setBackground(Color.white);
content.add(drawingArea, BorderLayout.WEST);
pack();
setVisible(true);
}
}