Java programming assignment: 1. Implement a method for KWArrayList (as a generic
ID: 669208 • Letter: J
Question
Java programming assignment:
1. Implement a method for KWArrayList (as a generic list) that removes an element from the end of the list and inserts it at the list’s beginning.
2. Following the example of Section 2.3 (see below), do not invoke other KWArrayList methods.
3. Write a test program proving that it works for ArrayLists having sizes 1, 2, 5.
import java.util.*;
/* This class implements some of the methods of the Java ArrayList class. */
public class KWArrayList<E> {
// Data fields
/* The default initial capacity */
private static final int INITIAL_CAPACITY = 10;
/* The underlying data array */
private E[] theData;
/* The current size */
private int size = 0;
/* The current capacity */
private int capacity = 0;
Explanation / Answer
1. program that removes trhe last element from the list and adds at the beginning:
import java.util.*;
public class LinkedList
{
public static void main(String args[])
{
LinkedList<string> LinkedList= new LinkedList<string>();
linkedlist.add("Ramya");
linkedlist.add("Praveen");
linkedlist.add("Joseph");
linkedlist.add("Antony");
linkedlist.add("Veeda");
System.oput.println("Linkedlist content:"+linkedlist);
object firstvar=linkedlist.get(0);
linkedlist.removelast();
System.out.println("Linkedlist after the deeletion of first item:"+linkedlist);
linkedlist.add(0,"Veeda");
System.out.println("Final content:"+linkedlist);
}
}
2. Adding and removing an element to and from the array list without invoking KWarraylist methods:
To remove an element:
import java.util.ArrayList;
import java.util.Arrays;
public class Remove
{
public static void main(String args[])
{
ArrayList<string> list=new ArrayList<string>(Arrays.aList(new String[]{"Ramya","Antony","Joseph"}));
list.remove(list.size()-1);
for(String item:list) System.out.printf("%s",item)
}
}
To Add an element:
import java.util.*;
class Add
{
public static void main(Styring args[])
{
ArrayList<string> listy=new ArrayList<string>();
system.out.println("initial size:"+list.size());
list.add(Chegg);
list.add(Cramster);
System.out.println("newsize:"+list.size());
for(int j=0;j<list.size();j++)
System.out.println("element"+j+":"+list.get(j));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.