SlideShare ist ein Scribd-Unternehmen logo
1 von 17
The Class ArrayLinearList
• General purpose implementation of linear lists.
• Unknown number of lists.
Create An Empty List
ArrayLinearList a = new ArrayLinearList(100),
b = new ArrayLinearList(),
c;
LinearList d = new ArrayLinearList(1000),
e = new ArrayLinearList(),
f;
Using A Linear List
System.out.println(a.size());
a.add(0, new Integer(2));
b.add(0, new Integer(4));
System.out.println(a);
b.remove(0);
if (a.isEmpty())
a.add(0, new Integer(5));
Array Of Linear Lists
LinearList [] x = new LinearList [4];
x[0] = new ArrayLinearList(20);
x[1] = new Chain();
x[2] = new Chain();
x[3] = new ArrayLinearList();
for (int i = 0; i < 4; i++)
x[i].add(0, new Integer(i));
The Class ArrayLinearList
/** array implementation of LinearList */
package dataStructures;
import java.util.*; // has Iterator interface
import utilities.*; // has array resizing class
public class ArrayLinearList implements LinearList
{
// data members
protected Object [] element; // array of elements
protected int size; // number of elements in array
// constructors and other methods come here
}
A Constructor
/** create a list with initial capacity initialCapacity
* @throws IllegalArgumentException when
* initialCapacity < 1 */
public ArrayLinearList(int initialCapacity)
{
if (initialCapacity < 1)
throw new IllegalArgumentException
("initialCapacity must be >= 1");
// size has the default initial value of 0
element = new Object [initialCapacity];
}
Another Constructor
/** create a list with initial capacity 10 */
public ArrayLinearList()
{// use default capacity of 10
this(10);
}
The Method isEmpty
/** @return true iff list is empty */
public boolean isEmpty()
{return size == 0;}
The Method size()
/** @return current number of elements in list */
public int size()
{return size;}
The Method checkIndex
/** @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1 */
void checkIndex(int index)
{
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
}
The Method get
/** @return element with specified index
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1 */
public Object get(int index)
{
checkIndex(index);
return element[index];
}
The Method indexOf
/** @return index of first occurrence of theElement,
* return -1 if theElement not in list */
public int indexOf(Object theElement)
{
// search element[] for theElement
for (int i = 0; i < size; i++)
if (element[i].equals(theElement))
return i;
// theElement not found
return -1;
}
The Method remove
public Object remove(int index)
{
checkIndex(index);
// valid index, shift elements with higher index
Object removedElement = element[index];
for (int i = index + 1; i < size; i++)
element[i-1] = element[i];
element[--size] = null; // enable garbage collection
return removedElement;
}
The Method add
public void add(int index, Object theElement)
{
if (index < 0 || index > size)
// invalid list position
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
// valid index, make sure we have space
if (size == element.length)
// no space, double capacity
element = ChangeArrayLength.changeLength1D(element, 2 *
size);
The Method add
// shift elements right one position
for (int i = size - 1; i >= index; i--)
element[i + 1] = element[i];
element[index] = theElement;
size++;
}
Faster Way To Shift Elements 1 Right
System.arraycopy(element, index, element,
index + 1, size - index);
Convert To A String
public String toString()
{
StringBuffer s = new StringBuffer("[");
// put elements into the buffer
for (int i = 0; i < size; i++)
if (element[i] == null) s.append("null, ");
else s.append(element[i].toString() + ", ");
if (size > 0) s.delete(s.length() - 2, s.length());
// remove last ", "
s.append("]");
// create equivalent String
return new String(s);
}

Weitere ähnliche Inhalte

Was ist angesagt?

งานนำเสนอ1
งานนำเสนอ1งานนำเสนอ1
งานนำเสนอ1
EveEim Elf
 
งานนำเสนอคอม
งานนำเสนอคอมงานนำเสนอคอม
งานนำเสนอคอม
EveEim Elf
 

Was ist angesagt? (20)

Dictionary and sets-converted
Dictionary and sets-convertedDictionary and sets-converted
Dictionary and sets-converted
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
งานนำเสนอ1
งานนำเสนอ1งานนำเสนอ1
งานนำเสนอ1
 
งานนำเสนอคอม
งานนำเสนอคอมงานนำเสนอคอม
งานนำเสนอคอม
 
F# array searching
F#  array searchingF#  array searching
F# array searching
 
Python set
Python setPython set
Python set
 
Python list
Python listPython list
Python list
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
Deletion of an element at a given particular position
Deletion of an  element  at a given particular positionDeletion of an  element  at a given particular position
Deletion of an element at a given particular position
 
Priority Queue
Priority QueuePriority Queue
Priority Queue
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Python lists
Python listsPython lists
Python lists
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
List in java
List in javaList in java
List in java
 

Andere mochten auch

Contents page stages
Contents page stagesContents page stages
Contents page stages
jackhorne
 
Ingrid CV Counseling English OCT 13 2016 final (1)
Ingrid CV Counseling English OCT 13 2016 final (1)Ingrid CV Counseling English OCT 13 2016 final (1)
Ingrid CV Counseling English OCT 13 2016 final (1)
Ingrid Masselink Andreas
 
_RSM-Resume16
_RSM-Resume16_RSM-Resume16
_RSM-Resume16
Roy Morum
 
Exame de pressão_arterial
Exame      de pressão_arterialExame      de pressão_arterial
Exame de pressão_arterial
João Martins
 
A digitális nemzedék tanulási stratégiája és tanulási környezete az iskolá...
A digitális nemzedék  tanulási stratégiája és  tanulási környezete  az iskolá...A digitális nemzedék  tanulási stratégiája és  tanulási környezete  az iskolá...
A digitális nemzedék tanulási stratégiája és tanulási környezete az iskolá...
Dr. Ollé János
 

Andere mochten auch (20)

Games ainal ikram
Games ainal ikramGames ainal ikram
Games ainal ikram
 
Contents page stages
Contents page stagesContents page stages
Contents page stages
 
Ingrid CV Counseling English OCT 13 2016 final (1)
Ingrid CV Counseling English OCT 13 2016 final (1)Ingrid CV Counseling English OCT 13 2016 final (1)
Ingrid CV Counseling English OCT 13 2016 final (1)
 
Animatic Storyboard Reel
Animatic Storyboard ReelAnimatic Storyboard Reel
Animatic Storyboard Reel
 
Presentacion sepiu unidis09
Presentacion sepiu unidis09Presentacion sepiu unidis09
Presentacion sepiu unidis09
 
CV
CVCV
CV
 
_RSM-Resume16
_RSM-Resume16_RSM-Resume16
_RSM-Resume16
 
Test
TestTest
Test
 
SOLIDS, LIQUIDS AND GASES
SOLIDS, LIQUIDS AND GASESSOLIDS, LIQUIDS AND GASES
SOLIDS, LIQUIDS AND GASES
 
Production Planning
Production PlanningProduction Planning
Production Planning
 
Styleguide: EXAMPLE 1
Styleguide: EXAMPLE 1Styleguide: EXAMPLE 1
Styleguide: EXAMPLE 1
 
kbs_resume
kbs_resumekbs_resume
kbs_resume
 
Exame de pressão_arterial
Exame      de pressão_arterialExame      de pressão_arterial
Exame de pressão_arterial
 
Functional onboarding through playful design
Functional onboarding through playful designFunctional onboarding through playful design
Functional onboarding through playful design
 
Jak zgodnie z prawem korzystać z dronów?
Jak zgodnie z prawem korzystać z dronów? Jak zgodnie z prawem korzystać z dronów?
Jak zgodnie z prawem korzystać z dronów?
 
Budget formulation - Ana Maria Ruiz, OECD
Budget formulation - Ana Maria Ruiz, OECDBudget formulation - Ana Maria Ruiz, OECD
Budget formulation - Ana Maria Ruiz, OECD
 
Marketing plan paytren
Marketing plan paytrenMarketing plan paytren
Marketing plan paytren
 
Проблемне навчання на уроках географії
Проблемне навчання на уроках географіїПроблемне навчання на уроках географії
Проблемне навчання на уроках географії
 
A digitális nemzedék tanulási stratégiája és tanulási környezete az iskolá...
A digitális nemzedék  tanulási stratégiája és  tanulási környezete  az iskolá...A digitális nemzedék  tanulási stratégiája és  tanulási környezete  az iskolá...
A digitális nemzedék tanulási stratégiája és tanulási környezete az iskolá...
 
Gamification Workshop 2010
Gamification Workshop 2010Gamification Workshop 2010
Gamification Workshop 2010
 

Ähnlich wie Engineering lecture ppt by venay magen

Illegal numbers.a. Complete the method find which accepts a collec.pdf
Illegal numbers.a. Complete the method find which accepts a collec.pdfIllegal numbers.a. Complete the method find which accepts a collec.pdf
Illegal numbers.a. Complete the method find which accepts a collec.pdf
gopalk44
 
import java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdfimport java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdf
anupamele
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
hemanth248901
 
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
fantoosh1
 
import java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdfimport java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdf
adhityalapcare
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
arpaqindia
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdf
access2future1
 
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docxweek4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
alanfhall8953
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
firstchoiceajmer
 
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
arshin9
 
Array based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdfArray based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdf
anithacells
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
adinathassociates
 
import java.util.ArrayList;public class ArrayListADT {   public .pdf
import java.util.ArrayList;public class ArrayListADT {   public .pdfimport java.util.ArrayList;public class ArrayListADT {   public .pdf
import java.util.ArrayList;public class ArrayListADT {   public .pdf
mohammadirfan136964
 

Ähnlich wie Engineering lecture ppt by venay magen (20)

Illegal numbers.a. Complete the method find which accepts a collec.pdf
Illegal numbers.a. Complete the method find which accepts a collec.pdfIllegal numbers.a. Complete the method find which accepts a collec.pdf
Illegal numbers.a. Complete the method find which accepts a collec.pdf
 
Design your own List ADT named StringList to provide the following .pdf
Design your own List ADT named StringList to provide the following .pdfDesign your own List ADT named StringList to provide the following .pdf
Design your own List ADT named StringList to provide the following .pdf
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructures
 
import java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdfimport java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdf
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
 
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
 
For this lab you will complete the class MyArrayList by implementing.pdf
For this lab you will complete the class MyArrayList by implementing.pdfFor this lab you will complete the class MyArrayList by implementing.pdf
For this lab you will complete the class MyArrayList by implementing.pdf
 
import java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdfimport java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdf
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdf
 
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
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docxweek4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.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
 
Array based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdfArray based based implementation of the List ADT It uses an array o.pdf
Array based based implementation of the List ADT It uses an array o.pdf
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
import java.util.ArrayList;public class ArrayListADT {   public .pdf
import java.util.ArrayList;public class ArrayListADT {   public .pdfimport java.util.ArrayList;public class ArrayListADT {   public .pdf
import java.util.ArrayList;public class ArrayListADT {   public .pdf
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

Engineering lecture ppt by venay magen

  • 1. The Class ArrayLinearList • General purpose implementation of linear lists. • Unknown number of lists.
  • 2. Create An Empty List ArrayLinearList a = new ArrayLinearList(100), b = new ArrayLinearList(), c; LinearList d = new ArrayLinearList(1000), e = new ArrayLinearList(), f;
  • 3. Using A Linear List System.out.println(a.size()); a.add(0, new Integer(2)); b.add(0, new Integer(4)); System.out.println(a); b.remove(0); if (a.isEmpty()) a.add(0, new Integer(5));
  • 4. Array Of Linear Lists LinearList [] x = new LinearList [4]; x[0] = new ArrayLinearList(20); x[1] = new Chain(); x[2] = new Chain(); x[3] = new ArrayLinearList(); for (int i = 0; i < 4; i++) x[i].add(0, new Integer(i));
  • 5. The Class ArrayLinearList /** array implementation of LinearList */ package dataStructures; import java.util.*; // has Iterator interface import utilities.*; // has array resizing class public class ArrayLinearList implements LinearList { // data members protected Object [] element; // array of elements protected int size; // number of elements in array // constructors and other methods come here }
  • 6. A Constructor /** create a list with initial capacity initialCapacity * @throws IllegalArgumentException when * initialCapacity < 1 */ public ArrayLinearList(int initialCapacity) { if (initialCapacity < 1) throw new IllegalArgumentException ("initialCapacity must be >= 1"); // size has the default initial value of 0 element = new Object [initialCapacity]; }
  • 7. Another Constructor /** create a list with initial capacity 10 */ public ArrayLinearList() {// use default capacity of 10 this(10); }
  • 8. The Method isEmpty /** @return true iff list is empty */ public boolean isEmpty() {return size == 0;}
  • 9. The Method size() /** @return current number of elements in list */ public int size() {return size;}
  • 10. The Method checkIndex /** @throws IndexOutOfBoundsException when * index is not between 0 and size - 1 */ void checkIndex(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException ("index = " + index + " size = " + size); }
  • 11. The Method get /** @return element with specified index * @throws IndexOutOfBoundsException when * index is not between 0 and size - 1 */ public Object get(int index) { checkIndex(index); return element[index]; }
  • 12. The Method indexOf /** @return index of first occurrence of theElement, * return -1 if theElement not in list */ public int indexOf(Object theElement) { // search element[] for theElement for (int i = 0; i < size; i++) if (element[i].equals(theElement)) return i; // theElement not found return -1; }
  • 13. The Method remove public Object remove(int index) { checkIndex(index); // valid index, shift elements with higher index Object removedElement = element[index]; for (int i = index + 1; i < size; i++) element[i-1] = element[i]; element[--size] = null; // enable garbage collection return removedElement; }
  • 14. The Method add public void add(int index, Object theElement) { if (index < 0 || index > size) // invalid list position throw new IndexOutOfBoundsException ("index = " + index + " size = " + size); // valid index, make sure we have space if (size == element.length) // no space, double capacity element = ChangeArrayLength.changeLength1D(element, 2 * size);
  • 15. The Method add // shift elements right one position for (int i = size - 1; i >= index; i--) element[i + 1] = element[i]; element[index] = theElement; size++; }
  • 16. Faster Way To Shift Elements 1 Right System.arraycopy(element, index, element, index + 1, size - index);
  • 17. Convert To A String public String toString() { StringBuffer s = new StringBuffer("["); // put elements into the buffer for (int i = 0; i < size; i++) if (element[i] == null) s.append("null, "); else s.append(element[i].toString() + ", "); if (size > 0) s.delete(s.length() - 2, s.length()); // remove last ", " s.append("]"); // create equivalent String return new String(s); }

Hinweis der Redaktion

  1. For the second example, the class ArrayLinearList must implement the interface LinearList. c and f are actually set to null. So, they really are not referencing an empty linear list but the null list. If ArrayLinearList has methods that are not listed in LinearList then we’ll need to typecast d,e,f to ALL before performing any of these additional methods ((ArrayLinearList) d).newMethod().
  2. Following first line, x[0:3] = null. The class Chain implements the interface LinearList. x[0].add(…) and x[3].add(…) invoke add method of ArrayLinearList while x[1].add and x[2].add result in the invocation of the add method of Chain.
  3. /** =&amp;gt; documentation comment. Used by javadoc to create html documentation files. The documentation files index.html, packages.html, etc. that are part of the codes that you have downloaded were produced by running javadoc. However, the above comment doesn’t appear in the produced documentation, because the doc comment must immediately precede the class, method, or field it applies to. Package statement must come first; import statements must come next. Packages are like folders, used to organize/store your programs in folders for easy access and permit name reuse across folders/packages. Import java.lang.* is implicit. Import statements specify a path relative to (or one that extends) a path contained in classpath. Default: visible in package only. Protected: in package and subclasses (I.e., classes that extend this one). Private: only in class. Public: visible to all classes in all packages.
  4. Note that code should verify input data and throw exceptions when this data is incorrect. Need have a throws statement in method header only if method throws an uncaught exception of type other than RuntimeException and Error.
  5. this(10) invokes the previous constructor.
  6. Note that checkIndex is not a public method. Visible only within the package. Could have made it protected instead. Then it would be visible only within the package dataStructures and classes that extend ALL.
  7. Note the use of the equals method. Default Object.equals method compares only references. This method must be overridden by user defined data types so that indexOf works correctly.
  8. s.delete(start, end) … deletes characters from start to end-1.