SlideShare a Scribd company logo
1 of 7
Download to read offline
Write a java class "LIST" that outputs:
//main:
public class AssignmentThree
{
public static void main(String[] args)
{
List myList = new List(15);
// Cause List Empty Message
myList.removeFront();
myList.removeRear();
myList.removeItem("a");
// Cause Not found message
myList.addToFront("x");
myList.removeItem("y");
myList.removeItem("x");
myList.addAfterItem("x", "z");
myList.addBeforeItem("x", "z");
// Normal behavior
myList.addToFront("not.");
myList.addToFront("or");
myList.addToRear("is");
myList.addToRear("try.");
myList.addAfterItem("is", "no");
myList.addBeforeItem("is", "There");
myList.addToFront("Do");
myList.addAfterItem("or", "do");
myList.print("Original list");
myList.printSorted("Sorted Original List");
sop(" Front is " + myList.getFront());
sop("Rear is " + myList.getRear());
sop("Count is " + myList.askCount());
sop("Is There present? " + myList.isPresent("There"));
sop("Is Dog present? " + myList.isPresent("Dog"));
myList.addToFront("junk");
myList.addToRear("morejunk");
myList.addAfterItem("or", "moremorejunk");
myList.print("List with junk");
sop("Count is " + myList.askCount());
myList.removeFront();
myList.removeRear();
myList.removeItem("moremorejunk");
myList.print("List with junk removed");
sop("Count is " + myList.askCount());
sop("");
// Cause List Full message
for(int ii = 0; ii < 10; ++ii)
{
myList.addToFront(DUMMY);
}
myList.addToRear(DUMMY);
myList.addBeforeItem("no", DUMMY);
myList.addAfterItem("There", DUMMY);
myList.print("After filling List");
sop("Count is " + myList.askCount());
while(myList.isPresent(DUMMY)) myList.removeItem(DUMMY);
myList.print("After removing " + DUMMY );
sop("Count is " + myList.askCount());
}
private static void sop(String s)
{
System.out.println(s);
}
private static final String DUMMY = "dummy";
}
//Class List:
public class List {
public List(int size)
{
}
public void addToFront(java.lang.String item)
{
}
public void addToRear(java.lang.String item)
{
}
public void addBeforeItem(java.lang.String beforeItem,
java.lang.String item)
{
}
public void addAfterItem(java.lang.String afterItem,
java.lang.String item)
{
}
public java.lang.String getFront()
{
}
public java.lang.String getRear()
{
}
public boolean isPresent(java.lang.String item)
{
}
public int askCount()
{
}
public void removeFront()
{
}
public void removeRear()
{
}
public void removeItem(java.lang.String item)
{
}
public void print(java.lang.String title)
{
}
public void printSorted(java.lang.String title)
{
}
}
Solution
The List is the base interface for all list types, and the ArrayList and LinkedList classes are two
common List’s implementations.
Besides ArrayList and LinkedList, Vector class is a legacy collection and later was retrofitted to
implement the Listinterface. Vector is thread-safe, but ArrayList and LinkedList are not. The
following class diagram depicts the inheritance tree of the List collections.
It’s a good practice to declare a list instance with a generic type parameter, for example:
1
2
3
4
List listAnything = new ArrayList();
List listWords = new ArrayList();
List listNumbers = new ArrayList();
List linkedWords = new LinkedList();
Since Java 7, we can remove the type parameter on the right side as follows:
1
2
List listNumbers = new ArrayList<>();
List linkedWords = new LinkedList<>();
The compiler is able to infer the actual type parameter from the declaration on the left side.
When creating a new ArrayList using the empty constructor, the list is constructed with an initial
capacity of ten. If you are sure how many elements will be added to the list, it’s recommended to
specify a capacity which is large enough. Let’s say, if we know that a list contains around 1000
elements, declare the list as follows:
1
List listNumbers = new ArrayList<>(1000);
It’s also possible to construct a list that takes elements from an existing collection, for example:
1
2
3
List listNumberOne; // existing collection
List listNumberTwo = new ArrayList<>(listNumberOne);
The listNumberTwo constructed with copies of all elements from the listNumberOne.The
methods add(Object), add(index, Object) and addAll() are used to add elements to the list. It
requires to add elements of the same type (or sub type) as the type parameter declared by the list.
For example:
1
2
3
4
5
6
7
8
9
List listStrings = new ArrayList();
// OK to add Strings:
listStrings.add("One");
listStrings.add("Two");
listStrings.add("Three");
// But this will cause compile error
listStrings.add(123);
Adding elements of sub types of the declared type:
1
2
3
4
5
6
List linkedNumbers = new LinkedList<>();
linkedNumbers.add(new Integer(123));
linkedNumbers.add(new Float(3.1415));
linkedNumbers.add(new Double(299.988));
linkedNumbers.add(new Long(67000));
We can insert an element into the list at a specified indexThe simplest way to sort out elements
in a list is using the Collections.sort() static method which sorts the specified list into ascending
order, based on the natural ordering of its elements. Here’s an example:
1
2
3
4
5
6
7
8
9
10
11
12
List listStrings = new ArrayList();
listStrings.add("D");
listStrings.add("C");
listStrings.add("E");
listStrings.add("A");
listStrings.add("B");
System.out.println("listStrings before sorting: " + listStrings);
Collections.sort(listStrings);
System.out.println("listStrings after sorting: " + listStrings);
Output:
1
2
listStrings before sorting: [D, C, E, A, B]
listStrings after sorting: [A, B, C, D, E]
1
2
3
4
List listAnything = new ArrayList();
List listWords = new ArrayList();
List listNumbers = new ArrayList();
List linkedWords = new LinkedList();

More Related Content

Similar to Java List Interface and Common Implementations

File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfConint29
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfclearvisioneyecareno
 
Write a method countUnique that takes a List of integers as a parame.pdf
Write a method countUnique that takes a List of integers as a parame.pdfWrite a method countUnique that takes a List of integers as a parame.pdf
Write a method countUnique that takes a List of integers as a parame.pdfMALASADHNANI
 
In this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdfIn this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdfEvanpZjSandersony
 
In this assignment you will implement insert() method for a singly l.pdf
In this assignment you will implement insert() method for a singly l.pdfIn this assignment you will implement insert() method for a singly l.pdf
In this assignment you will implement insert() method for a singly l.pdffantasiatheoutofthef
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 The MyLinkedList class used in Listing 24.6 is a one-way directional .docx The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
The MyLinkedList class used in Listing 24.6 is a one-way directional .docxKomlin1
 
Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxStewartt0kJohnstonh
 
When we first examined the array based and node based implementations.docx
 When we first examined the array based and node based implementations.docx When we first examined the array based and node based implementations.docx
When we first examined the array based and node based implementations.docxajoy21
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23HUST
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23HUST
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdffantoosh1
 
Java AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdfJava AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdfambersushil
 
Write a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfWrite a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfinfo785431
 

Similar to Java List Interface and Common Implementations (20)

File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Write a method countUnique that takes a List of integers as a parame.pdf
Write a method countUnique that takes a List of integers as a parame.pdfWrite a method countUnique that takes a List of integers as a parame.pdf
Write a method countUnique that takes a List of integers as a parame.pdf
 
In this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdfIn this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdf
 
In this assignment you will implement insert() method for a singly l.pdf
In this assignment you will implement insert() method for a singly l.pdfIn this assignment you will implement insert() method for a singly l.pdf
In this assignment you will implement insert() method for a singly l.pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 The MyLinkedList class used in Listing 24.6 is a one-way directional .docx The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 
Data structures
Data structures Data structures
Data structures
 
Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docx
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
When we first examined the array based and node based implementations.docx
 When we first examined the array based and node based implementations.docx When we first examined the array based and node based implementations.docx
When we first examined the array based and node based implementations.docx
 
Collections
CollectionsCollections
Collections
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23
 
Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdf
 
Array list(1)
Array list(1)Array list(1)
Array list(1)
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Java AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdfJava AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdf
 
Write a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfWrite a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdf
 

More from ebrahimbadushata00

irktors (lcloding his accoueting instructor thmivenity c. All student.pdf
irktors (lcloding his accoueting instructor thmivenity c. All student.pdfirktors (lcloding his accoueting instructor thmivenity c. All student.pdf
irktors (lcloding his accoueting instructor thmivenity c. All student.pdfebrahimbadushata00
 
Is there a solution manual to group dynamics for team (fourth Editio.pdf
Is there a solution manual to group dynamics for team (fourth Editio.pdfIs there a solution manual to group dynamics for team (fourth Editio.pdf
Is there a solution manual to group dynamics for team (fourth Editio.pdfebrahimbadushata00
 
IntroductionFor this program, you will implement an interface that.pdf
IntroductionFor this program, you will implement an interface that.pdfIntroductionFor this program, you will implement an interface that.pdf
IntroductionFor this program, you will implement an interface that.pdfebrahimbadushata00
 
In Python,Create a program that asks the user for a number and the.pdf
In Python,Create a program that asks the user for a number and the.pdfIn Python,Create a program that asks the user for a number and the.pdf
In Python,Create a program that asks the user for a number and the.pdfebrahimbadushata00
 
In contrast to sexual reproduction in animals, sexually-reproducing .pdf
In contrast to sexual reproduction in animals, sexually-reproducing .pdfIn contrast to sexual reproduction in animals, sexually-reproducing .pdf
In contrast to sexual reproduction in animals, sexually-reproducing .pdfebrahimbadushata00
 
Ignore what I have written because Im pretty sure its wrong. Thank.pdf
Ignore what I have written because Im pretty sure its wrong. Thank.pdfIgnore what I have written because Im pretty sure its wrong. Thank.pdf
Ignore what I have written because Im pretty sure its wrong. Thank.pdfebrahimbadushata00
 
How can crisis leadership be learnedSolutionAn organization n.pdf
How can crisis leadership be learnedSolutionAn organization n.pdfHow can crisis leadership be learnedSolutionAn organization n.pdf
How can crisis leadership be learnedSolutionAn organization n.pdfebrahimbadushata00
 
Given the following information on a project develop early and la.pdf
Given the following information on a project develop early and la.pdfGiven the following information on a project develop early and la.pdf
Given the following information on a project develop early and la.pdfebrahimbadushata00
 
Global Economy, National Economies, and CompetitionIn the first pa.pdf
Global Economy, National Economies, and CompetitionIn the first pa.pdfGlobal Economy, National Economies, and CompetitionIn the first pa.pdf
Global Economy, National Economies, and CompetitionIn the first pa.pdfebrahimbadushata00
 
Explain why owners equity includes common stock as a liability eve.pdf
Explain why owners equity includes common stock as a liability eve.pdfExplain why owners equity includes common stock as a liability eve.pdf
Explain why owners equity includes common stock as a liability eve.pdfebrahimbadushata00
 
Evaluate the statements below and determine which is the best reason.pdf
Evaluate the statements below and determine which is the best reason.pdfEvaluate the statements below and determine which is the best reason.pdf
Evaluate the statements below and determine which is the best reason.pdfebrahimbadushata00
 
Discuss the Economic Benefits from Immigration.SolutionImmigra.pdf
Discuss the Economic Benefits from Immigration.SolutionImmigra.pdfDiscuss the Economic Benefits from Immigration.SolutionImmigra.pdf
Discuss the Economic Benefits from Immigration.SolutionImmigra.pdfebrahimbadushata00
 
Conclusion Phases of Oxidative Phosphorylation Focus your attention.pdf
Conclusion Phases of Oxidative Phosphorylation  Focus your attention.pdfConclusion Phases of Oxidative Phosphorylation  Focus your attention.pdf
Conclusion Phases of Oxidative Phosphorylation Focus your attention.pdfebrahimbadushata00
 
Computer Forensics Process Please respond to the followingThe.pdf
Computer Forensics Process Please respond to the followingThe.pdfComputer Forensics Process Please respond to the followingThe.pdf
Computer Forensics Process Please respond to the followingThe.pdfebrahimbadushata00
 
ArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdf
ArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdfArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdf
ArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdfebrahimbadushata00
 
Can someone solveexplain this I thought I was understanding this, .pdf
Can someone solveexplain this I thought I was understanding this, .pdfCan someone solveexplain this I thought I was understanding this, .pdf
Can someone solveexplain this I thought I was understanding this, .pdfebrahimbadushata00
 
C The ame compound componda with F Souls . E Difluut eoupou ds with.pdf
C The ame compound componda with F Souls . E  Difluut eoupou ds with.pdfC The ame compound componda with F Souls . E  Difluut eoupou ds with.pdf
C The ame compound componda with F Souls . E Difluut eoupou ds with.pdfebrahimbadushata00
 
Background Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdf
Background Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdfBackground Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdf
Background Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdfebrahimbadushata00
 
a. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdf
a. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdfa. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdf
a. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdfebrahimbadushata00
 
A severe B12 deficiency can cause megaloblastic anemia but in severe .pdf
A severe B12 deficiency can cause megaloblastic anemia but in severe .pdfA severe B12 deficiency can cause megaloblastic anemia but in severe .pdf
A severe B12 deficiency can cause megaloblastic anemia but in severe .pdfebrahimbadushata00
 

More from ebrahimbadushata00 (20)

irktors (lcloding his accoueting instructor thmivenity c. All student.pdf
irktors (lcloding his accoueting instructor thmivenity c. All student.pdfirktors (lcloding his accoueting instructor thmivenity c. All student.pdf
irktors (lcloding his accoueting instructor thmivenity c. All student.pdf
 
Is there a solution manual to group dynamics for team (fourth Editio.pdf
Is there a solution manual to group dynamics for team (fourth Editio.pdfIs there a solution manual to group dynamics for team (fourth Editio.pdf
Is there a solution manual to group dynamics for team (fourth Editio.pdf
 
IntroductionFor this program, you will implement an interface that.pdf
IntroductionFor this program, you will implement an interface that.pdfIntroductionFor this program, you will implement an interface that.pdf
IntroductionFor this program, you will implement an interface that.pdf
 
In Python,Create a program that asks the user for a number and the.pdf
In Python,Create a program that asks the user for a number and the.pdfIn Python,Create a program that asks the user for a number and the.pdf
In Python,Create a program that asks the user for a number and the.pdf
 
In contrast to sexual reproduction in animals, sexually-reproducing .pdf
In contrast to sexual reproduction in animals, sexually-reproducing .pdfIn contrast to sexual reproduction in animals, sexually-reproducing .pdf
In contrast to sexual reproduction in animals, sexually-reproducing .pdf
 
Ignore what I have written because Im pretty sure its wrong. Thank.pdf
Ignore what I have written because Im pretty sure its wrong. Thank.pdfIgnore what I have written because Im pretty sure its wrong. Thank.pdf
Ignore what I have written because Im pretty sure its wrong. Thank.pdf
 
How can crisis leadership be learnedSolutionAn organization n.pdf
How can crisis leadership be learnedSolutionAn organization n.pdfHow can crisis leadership be learnedSolutionAn organization n.pdf
How can crisis leadership be learnedSolutionAn organization n.pdf
 
Given the following information on a project develop early and la.pdf
Given the following information on a project develop early and la.pdfGiven the following information on a project develop early and la.pdf
Given the following information on a project develop early and la.pdf
 
Global Economy, National Economies, and CompetitionIn the first pa.pdf
Global Economy, National Economies, and CompetitionIn the first pa.pdfGlobal Economy, National Economies, and CompetitionIn the first pa.pdf
Global Economy, National Economies, and CompetitionIn the first pa.pdf
 
Explain why owners equity includes common stock as a liability eve.pdf
Explain why owners equity includes common stock as a liability eve.pdfExplain why owners equity includes common stock as a liability eve.pdf
Explain why owners equity includes common stock as a liability eve.pdf
 
Evaluate the statements below and determine which is the best reason.pdf
Evaluate the statements below and determine which is the best reason.pdfEvaluate the statements below and determine which is the best reason.pdf
Evaluate the statements below and determine which is the best reason.pdf
 
Discuss the Economic Benefits from Immigration.SolutionImmigra.pdf
Discuss the Economic Benefits from Immigration.SolutionImmigra.pdfDiscuss the Economic Benefits from Immigration.SolutionImmigra.pdf
Discuss the Economic Benefits from Immigration.SolutionImmigra.pdf
 
Conclusion Phases of Oxidative Phosphorylation Focus your attention.pdf
Conclusion Phases of Oxidative Phosphorylation  Focus your attention.pdfConclusion Phases of Oxidative Phosphorylation  Focus your attention.pdf
Conclusion Phases of Oxidative Phosphorylation Focus your attention.pdf
 
Computer Forensics Process Please respond to the followingThe.pdf
Computer Forensics Process Please respond to the followingThe.pdfComputer Forensics Process Please respond to the followingThe.pdf
Computer Forensics Process Please respond to the followingThe.pdf
 
ArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdf
ArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdfArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdf
ArticleHinduism and Caste Systemby Jayaram VHinduism is a univ.pdf
 
Can someone solveexplain this I thought I was understanding this, .pdf
Can someone solveexplain this I thought I was understanding this, .pdfCan someone solveexplain this I thought I was understanding this, .pdf
Can someone solveexplain this I thought I was understanding this, .pdf
 
C The ame compound componda with F Souls . E Difluut eoupou ds with.pdf
C The ame compound componda with F Souls . E  Difluut eoupou ds with.pdfC The ame compound componda with F Souls . E  Difluut eoupou ds with.pdf
C The ame compound componda with F Souls . E Difluut eoupou ds with.pdf
 
Background Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdf
Background Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdfBackground Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdf
Background Sometimes the standard C libraries (stdio.h, stdlib.h, e.pdf
 
a. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdf
a. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdfa. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdf
a. Modify the C program ex.9 so that it simulates the Unix pipe comm.pdf
 
A severe B12 deficiency can cause megaloblastic anemia but in severe .pdf
A severe B12 deficiency can cause megaloblastic anemia but in severe .pdfA severe B12 deficiency can cause megaloblastic anemia but in severe .pdf
A severe B12 deficiency can cause megaloblastic anemia but in severe .pdf
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Java List Interface and Common Implementations

  • 1. Write a java class "LIST" that outputs: //main: public class AssignmentThree { public static void main(String[] args) { List myList = new List(15); // Cause List Empty Message myList.removeFront(); myList.removeRear(); myList.removeItem("a"); // Cause Not found message myList.addToFront("x"); myList.removeItem("y"); myList.removeItem("x"); myList.addAfterItem("x", "z"); myList.addBeforeItem("x", "z"); // Normal behavior myList.addToFront("not."); myList.addToFront("or"); myList.addToRear("is"); myList.addToRear("try."); myList.addAfterItem("is", "no"); myList.addBeforeItem("is", "There"); myList.addToFront("Do"); myList.addAfterItem("or", "do"); myList.print("Original list"); myList.printSorted("Sorted Original List"); sop(" Front is " + myList.getFront()); sop("Rear is " + myList.getRear());
  • 2. sop("Count is " + myList.askCount()); sop("Is There present? " + myList.isPresent("There")); sop("Is Dog present? " + myList.isPresent("Dog")); myList.addToFront("junk"); myList.addToRear("morejunk"); myList.addAfterItem("or", "moremorejunk"); myList.print("List with junk"); sop("Count is " + myList.askCount()); myList.removeFront(); myList.removeRear(); myList.removeItem("moremorejunk"); myList.print("List with junk removed"); sop("Count is " + myList.askCount()); sop(""); // Cause List Full message for(int ii = 0; ii < 10; ++ii) { myList.addToFront(DUMMY); } myList.addToRear(DUMMY); myList.addBeforeItem("no", DUMMY); myList.addAfterItem("There", DUMMY); myList.print("After filling List"); sop("Count is " + myList.askCount()); while(myList.isPresent(DUMMY)) myList.removeItem(DUMMY); myList.print("After removing " + DUMMY ); sop("Count is " + myList.askCount()); }
  • 3. private static void sop(String s) { System.out.println(s); } private static final String DUMMY = "dummy"; } //Class List: public class List { public List(int size) { } public void addToFront(java.lang.String item) { } public void addToRear(java.lang.String item) { } public void addBeforeItem(java.lang.String beforeItem, java.lang.String item) { } public void addAfterItem(java.lang.String afterItem, java.lang.String item) { } public java.lang.String getFront() { }
  • 4. public java.lang.String getRear() { } public boolean isPresent(java.lang.String item) { } public int askCount() { } public void removeFront() { } public void removeRear() { } public void removeItem(java.lang.String item) { } public void print(java.lang.String title) { } public void printSorted(java.lang.String title) { } } Solution
  • 5. The List is the base interface for all list types, and the ArrayList and LinkedList classes are two common List’s implementations. Besides ArrayList and LinkedList, Vector class is a legacy collection and later was retrofitted to implement the Listinterface. Vector is thread-safe, but ArrayList and LinkedList are not. The following class diagram depicts the inheritance tree of the List collections. It’s a good practice to declare a list instance with a generic type parameter, for example: 1 2 3 4 List listAnything = new ArrayList(); List listWords = new ArrayList(); List listNumbers = new ArrayList(); List linkedWords = new LinkedList(); Since Java 7, we can remove the type parameter on the right side as follows: 1 2 List listNumbers = new ArrayList<>(); List linkedWords = new LinkedList<>(); The compiler is able to infer the actual type parameter from the declaration on the left side. When creating a new ArrayList using the empty constructor, the list is constructed with an initial capacity of ten. If you are sure how many elements will be added to the list, it’s recommended to specify a capacity which is large enough. Let’s say, if we know that a list contains around 1000 elements, declare the list as follows: 1 List listNumbers = new ArrayList<>(1000); It’s also possible to construct a list that takes elements from an existing collection, for example: 1 2 3 List listNumberOne; // existing collection List listNumberTwo = new ArrayList<>(listNumberOne); The listNumberTwo constructed with copies of all elements from the listNumberOne.The methods add(Object), add(index, Object) and addAll() are used to add elements to the list. It requires to add elements of the same type (or sub type) as the type parameter declared by the list. For example:
  • 6. 1 2 3 4 5 6 7 8 9 List listStrings = new ArrayList(); // OK to add Strings: listStrings.add("One"); listStrings.add("Two"); listStrings.add("Three"); // But this will cause compile error listStrings.add(123); Adding elements of sub types of the declared type: 1 2 3 4 5 6 List linkedNumbers = new LinkedList<>(); linkedNumbers.add(new Integer(123)); linkedNumbers.add(new Float(3.1415)); linkedNumbers.add(new Double(299.988)); linkedNumbers.add(new Long(67000)); We can insert an element into the list at a specified indexThe simplest way to sort out elements in a list is using the Collections.sort() static method which sorts the specified list into ascending order, based on the natural ordering of its elements. Here’s an example: 1 2 3 4 5
  • 7. 6 7 8 9 10 11 12 List listStrings = new ArrayList(); listStrings.add("D"); listStrings.add("C"); listStrings.add("E"); listStrings.add("A"); listStrings.add("B"); System.out.println("listStrings before sorting: " + listStrings); Collections.sort(listStrings); System.out.println("listStrings after sorting: " + listStrings); Output: 1 2 listStrings before sorting: [D, C, E, A, B] listStrings after sorting: [A, B, C, D, E] 1 2 3 4 List listAnything = new ArrayList(); List listWords = new ArrayList(); List listNumbers = new ArrayList(); List linkedWords = new LinkedList();