I am trying to write a removeFirst method for an ArrayList of the generic type. The removeFirst method is supposed to do a few things: 1) If the list is empty it throws an error. 2) It stores the data in a node pointed to by head. 3) Set the head to head's next. 4) decrement the size. 5) returns the data. I can do 1,4, and 5 but I am stuck on 2 and 3. Here is the code I have so far. Please take a look and give me a hint or suggestion:
=============== =============== =============== ============
public class ArrayList<T> implements ListADT<T>
{
protected final int DEFAULT_CAPACIT Y = 100;
private final int NOT_FOUND = -1;
protected int rear;
protected T[] list;
//-----------------------------------------------------------------
// Creates an empty list using the default capacity.
//-----------------------------------------------------------------
public ArrayList()
{
rear = 0;
list = (T[])(new Object[DEFAULT_CAPACIT Y]);
}
//-----------------------------------------------------------------
// Creates an empty list using the specified capacity.
//-----------------------------------------------------------------
public ArrayList (int initialCapacity )
{
rear = 0;
list = (T[])(new Object[initialCapacity]);
}
//-----------------------------------------------------------------
// Removes and returns the first element in the list.
//-----------------------------------------------------------------
public T removeFirst()th rows EmptyCollection Exception
{
if (rear == 0)
throw new EmptyCollection Exception("Tryi ng to remove first element");
return result;
}
//-----------------------------------------------------------------
// Removes and returns the specified element.
//-----------------------------------------------------------------
public T remove (T element)
{
T result;
int index = find (element);
if (index == NOT_FOUND)
throw new ElementNotFound Exception ("list");
result = list[index];
rear--;
// shift the appropriate elements
for (int scan=index; scan < rear; scan++)
list[scan] = list[scan+1];
list[rear] = null;
return result;
}
//-----------------------------------------------------------------
// Returns a reference to the element at the front of the list.
// The element is not removed from the list. Throws an
// EmptyCollection Exception if the list is empty.
//-----------------------------------------------------------------
public T first() throws EmptyCollection Exception
{ return result;
}
//-----------------------------------------------------------------
// Returns a reference to the element at the rear of the list.
// The element is not removed from the list. Throws an
// EmptyCollection Exception if the list is empty.
//-----------------------------------------------------------------
public T last() throws EmptyCollection Exception
{ return result;
}
//-----------------------------------------------------------------
// Returns true if this list contains the specified element.
//-----------------------------------------------------------------
public boolean contains (T target)
{
return (find(target) != NOT_FOUND);
}
//-----------------------------------------------------------------
// Returns the array index of the specified element, or the
// constant NOT_FOUND if it is not found.
//-----------------------------------------------------------------
private int find (T target)
{
int scan = 0, result = NOT_FOUND;
boolean found = false;
if (! isEmpty())
while (! found && scan < rear)
if (target.equals( list[scan]))
found = true;
else
scan++;
if (found)
result = scan;
return result;
}
//-----------------------------------------------------------------
// Returns true if this list is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty()
{
return (rear==0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this list.
//-----------------------------------------------------------------
public int size()
{
return rear;
}
//-----------------------------------------------------------------
// Returns an iterator for the elements currently in this list.
//-----------------------------------------------------------------
public Iterator<T> iterator()
{
return new ArrayIterator<T > (list, rear);
}
//-----------------------------------------------------------------
// Returns a string representation of this list.
//-----------------------------------------------------------------
public String toString()
{
String result = " ";
for (int index = 0; index < rear; index++)
result = result + list[index].toString() + "\n";
return result;
}
//-----------------------------------------------------------------
// Creates a new array to store the contents of the list with
// twice the capacity of the old one.
//-----------------------------------------------------------------
protected void expandCapacity( )
{
T[] larger = (T[])(new Object[list.length*2]);
for (int scan=0; scan < list.length; scan++)
larger[scan] = list[scan];
list = larger;
}
}
7 3824 DeMan 1,806
Top Contributor
It appears you are implementing the whole type?
While implementing it with an array will work, can I suggest that you try to use an actual linked list. Java is reasonably simple for this, and you will find that insert and remove methods will be more efficient...
Unless you are required to use an array for this , I would try to avoid it....
The 2nd part of the project is to do the same methods with a LinkedList in mind so that we can see the time variance between the two with a sample driver class that the teacher has produced. My problem right now is that I am lost on writing the removeFirst method.
DeMan 1,806
Top Contributor
Inefficient I know....
Since you are using arrays, you know that this element is in list[0], and we don't really even have to delete him, we can copy list[1] over him, list[2] over list[1] ETC...
Pseudocode (probably more javanese than anything) -
for(i=0 to list.size-1) //or length
-
{
-
list[i]=list[i+1]
-
}
-
list[list.size] = NULL; //or zero or whatever you need to do to delete
-
This is what I came up with on my own, tell me what you think.
=============== =============== =============== =========
public T removeFirst()th rows EmptyCollection Exception
{
T result;
if (rear == 0)
throw new EmptyCollection Exception("Tryi ng to remove first element");
result = list[rear];
rear --;
return result;
}
DeMan 1,806
Top Contributor
Depending on how you implement your list (like if you stored the first element at the bac) that would work. Can I just clarify that we ARE trying to create a list structure? Because I sus[ect you're trying to create a stack......
Also, since I'm being Pinickity (??) can I suggest that you enclose your code in code tags for easier reading (by using the # button above).
Sorry about the long code I displayed. Anyway, I figured it all out, but thanks for the help.
Sorry about the long code I displayed. Anyway, I figured it all out, but thanks for the help.
Posting long code is not a problem as long as you enclose it in code tags.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Jamus Sprinson |
last post by:
Before I continue, I'm going to begin by saying I'm not by any means
an expert- I've been using .NET with C# for about 4 months now, and
basically just learning by example and docs.
A game project I work on uses Xml serialization to store game objects
for loading. One of the techniques we use is to make an array
property and use the set block to perform actions on the values after
they're loaded from the xml, as in:
public string Ids
|
by: Eric |
last post by:
I'm looking at this page in the MSDN right here:
ms-help://MS.MSDNQTR.2003FEB.1033/cpref/html/frlrfsystemcollectionsarraylist
classsynchronizedtopic2.htm
(or online here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcollectionsicollectionclasssyncroottopic.asp)
And I'm interested in locking an ArrayList during the entire enumeration, as
shown in the example code. My problem is that I'm STILL...
|
by: Hans De Schrijver |
last post by:
I have a private ArrayList variable that holds objects of various types,
though they're all derived from a common base class (User).
What I would like to do is provide public accessor properties per type. I
have written some code that does the trick now, but it involves looping
through the private ArrayList and creating a new Array with just the objects
of the type corresponding to the property. Problem is, this hapens every
time you...
|
by: Sylvain |
last post by:
Hi,
I'm encountering a very simple issue with ArrayList constructor
and AddRange() method overriding.
I'm defining a class that extends ArrayList and contains one
overriden method: AddRange(ICollection).
public class Test:ArrayList
{
|
by: C Downey |
last post by:
Hello:
I have an arraylist storing some very basic objects.
The object is very basic, it has 2 properties : ID, and COUNT
Before I add an object to the arraylist, I want to check if an object with
that same ID already exists in the arraylist.
If it does, I would like to increase the count of the matching object inside
| |
by: Rubbrecht Philippe |
last post by:
Hi there,
According to documentation I read the ArrayList.IndexOf method uses the
Object.Equals method to loop through the items in its list and locate the
first index of an item that returns True.
Therefore, overriding the Equals method in the class definition of the items
I put in the ArrayList should make the IndexOf method use my version of the
Equals method?!
|
by: JohnR |
last post by:
From reading the documentation, this should be a relatively easy thing. I
have an arraylist of custom class instances which I want to search with
an"indexof" where I'm passing an instance if the class where only the
"searched" property has a value. I expected to get the index into the
arraylist where I could then get the entire class instance. However, the
'indexof' is never calling my overloaded, overrides Equals method. Here is
the...
|
by: Alex Chudnovsky |
last post by:
I have come across with what appears to be a significant performance bug in
..NET 2.0 ArrayList.Sort method when compared with Array.Sort on the same
data. Same data on the same CPU gets sorted a lot faster with both methods
using .NET 1.1, that's why I am pretty sure its a (rather serious) bug. Below
you can find C# test case that should allow you to reproduce this error, to
run it you will need to put 2 data files into current directory...
|
by: blt51 |
last post by:
I need to write a program that handles a bank account and does a number of transactions using an arraylist. However, I'm having trouble getting the arraylist to store all the transactions and then output them. There are 2 classes, Bank and BankAccount. I also have a tester. Any help would be appreciated.
Bank
package bank;
import java.util.ArrayList;
/**
This bank contains a collection of bank accounts.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |