Question

10.3 Example. When you first declare a new list, it is empty and its length is...

10.3 Example. When you first declare a new list, it is empty and its length is zero. If you add three objects—a, b, and c—one at a time and in the order given, to the end of the list, the list will appear as

a b c

The object a is first, at position 1, b is at position 2, and c is last at position 3.1 To save space here, we will sometimes write a list’s contents on one line. For example, we might write

1. Some people number the entries in a list beginning with 0 instead of 1.
abc
to represent this list.
The following pseudocode represents the previous three additions to the specific list myList:

myList.add(a) myList.add(b) myList.add(c)

At this point, myList is not empty, so myList.isEmpty() is false. Since the list contains three entries,myList.getLength() is 3. Notice that adding entries to the end of a list does not change the positions of entries already in the list.

Write a Java program to do the six ADT list operations shown in Figure 10-2, p297, and display the final list. Use the JavaClassLibrary List (see page 308) for the interface and ArrayListfor the implementation.

Is it better to number the entries in a list beginning with 0 instead of 1?

Attach the lab and copyAndPaste the output. SR

Figure 10-2

Java Class Library: The Interface List

1. 10.19 The standard package java.util contains an interface List for an ADT list that is similar to the list that our interface describes. One difference between a list in the Java Class Library and our ADT list is the numbering of a list’s entries. A list in the Java Class Library uses the same numbering scheme as a Java array: The first entry is at position, or index, 0. In contrast, we begin our list at position 1. The interface List also declares more methods than our interface does. You’ll see a few of those additional methods in Java Interlude 4.

The following method headers from the interface List are for a selection of methods that are similar to the ones you have seen in this chapter. We have highlighted where they differ from our methods. Once again, T is the generic type of the entries in the list.

public boolean add(T newEntry)
public void add(int index, T newEntry)
public T remove(int index)
public void clear()
public T set(int index, T anEntry) // Like replace public T get(int index) // Like getEntry public boolean contains(Object anEntry)
public int size() // Like getLength public boolean isEmpty()

The first add method, which adds an entry to the end of a list, returns a boolean value, whereas our analogous method is a void method. The method set is like our replace method, and the method get is like our method getEntry. The data type of contains’ parameter is Object instead of a generic type. In practice, this difference has little consequence. Lastly, the method size is like our getLength.

You can learn more about the interface List in the online documentation for the Java Class Library.

Java Class Library: The Class ArrayList

10.20 The Java Class Library contains an implementation of the ADT list that uses a resizable array. This class, called ArrayList, implements the interface java.util.List, that we just discussed. The class also is in the package java.util.

Two of the constructors available for ArrayList are as follows: public ArrayList()

Creates an empty list with an initial capacity of 10. The list increases its capacity as needed by an unspecified amount.

public ArrayList(int initialCapacity)
Creates an empty list with the specified initial capacity. The list increases its capacity as needed by an

unspecified amount.

10.21 The class java.util.Vector, which we described in Chapter 6 , is similar to ArrayList. Both classes implement the same interfaces: java.util.List, as well as others. Even so, Vector contains a few more methods than ArrayList. We will ignore these extra methods, as they mostly are redundant.

You can use either ArrayList or Vector as an implementation of the interface List. For example, you could write either of the following statements to define a list of strings:

List<String> myList = new ArrayList<>();
or
List<string> myList = new Vector<>();
Now myList has only the methods declared in the interface List.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.ArrayList;
import java.util.List;

public class ListOperations<T> {
    public static void main(String[] args) {
        List<String> myList = new ArrayList<>();
        // add item to the list
        myList.add("a");
        myList.add("c");
        // add item to the specified index of list
        myList.add(1, "b");
        System.out.println("List:");
        for(int i=0;i<myList.size();i++)
            System.out.print(myList.get(i)+" ");
        System.out.println();
        System.out.println("check 'b' is in the list or not");
        System.out.println(myList.contains("b"));
        System.out.println("check 'd' is in the list or not");
        System.out.println(myList.contains("d"));
        System.out.println("Number of items in the list");
        System.out.println(myList.size());
        System.out.println("Remove item in the position 1");
        myList.remove(1);
        System.out.println("List after removal");
        for(int i=0;i<myList.size();i++)
            System.out.print(myList.get(i));
        System.out.println();
        System.out.println("Remove all items");
        myList.clear();
        System.out.println("List after removal");
        for(int i=0;i<myList.size();i++)
            System.out.print(myList.get(i));
        System.out.println();
        System.out.println("check list is emty or not");
        System.out.println(myList.isEmpty());
    }
}

OUTPUT

Array is continuous space in memory. And OS stores the address from where elements start. Assume address of first element is 1001. If we want to know 10th element, it will be at an offset on 10 from 1001. So, offset is the reason why array indices start from 0.

Add a comment
Know the answer?
Add Answer to:
10.3 Example. When you first declare a new list, it is empty and its length is...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Problem 3 (List Implementation) (35 points): Write a method in the DoublyLList class that deletes the...

    Problem 3 (List Implementation) (35 points): Write a method in the DoublyLList class that deletes the first item containing a given value from a doubly linked list. The header of the method is as follows: public boolean removeValue(T aValue) where T is the general type of the objects in the list and the methods returns true if such an item is found and deleted. Include testing of the method in a main method of the DoublyLList class. ------------------------------------------------------------------------------------- /** A...

  • Write a Java program to work with a generic list ADT using a fixed size array,...

    Write a Java program to work with a generic list ADT using a fixed size array, not ArrayList. Create the interface ListInterface with the following methods a) add(newEntry): Adds a new entry to the end of the list. b) add(newPosition, newEntry): Adds a new entry to the list at a given position. c) remove(givenPosition): Removes the entry at a given position from the list. d) clear( ): Removes all entries from the list . e) replace(givenPosition, newEntry): Replaces the entry...

  • Create a java class that implements BagInterface using singly linked data. Name this new class LinkedBag....

    Create a java class that implements BagInterface using singly linked data. Name this new class LinkedBag. Be sure to include a default constructor to initialize the private members of the class. Test that your code works properly. BagInterface includes the methods:  public int getCurrentSize(); public boolean isEmpty(); public boolean add(T newEntry); public T remove(); public boolean remove(T anEntry); public void clear(); public int getFrequencyOf(T anEntry); public boolean contains(T anEntry); public T[] toArray();

  • Write a JAVA contains method for a linked implementation of a sorted list. #This method is...

    Write a JAVA contains method for a linked implementation of a sorted list. #This method is written from the implementation perspective, meaning it would go inside of the LinkedSortedList class. This means we have access to firstNode and numberOfEntries. #write an efficient solution. This will involve directly accessing the linked structure rather than only invoking existing methods. You can assume T is Comparable. #The method header is: public boolean contains(T anEntry)

  • Complete an Array-Based implementation of the ADT List including a main method and show that the...

    Complete an Array-Based implementation of the ADT List including a main method and show that the ADT List works. Draw a class diagram of the ADT List __________________________________________ public interface IntegerListInterface{ public boolean isEmpty(); //Determines whether a list is empty. //Precondition: None. //Postcondition: Returns true if the list is empty, //otherwise returns false. //Throws: None. public int size(); // Determines the length of a list. // Precondition: None. // Postcondition: Returns the number of items in this IntegerList. //Throws: None....

  • Create a Java code that includes all the methods from the Lecture slides following the ADTs...

    Create a Java code that includes all the methods from the Lecture slides following the ADTs LECTURE SLIDE Collect/finish the Java code (interface and the complete working classes) from lecture slides for the following ADTS 2) ArrayList ADT that uses a linked list internally (call it LArrayList) Make sure you keep the same method names as in the slides (automatic testing will be performed)! For each method you develop, add comments and estimate the big-O running time of its algorithm....

  • Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the...

    Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the overlapping content of the bags. Intersections are explained in more detail in Chapter 1, #6. An intersecion might contain duplicates. The method should not alter either bag. The current bag and the bag sent in as a parameter should be the same when the method ends. The method header is: public BagInterface<T> intersection(ResizableArrayBag <T> anotherBag) Example: bag1 contains (1, 2, 2, 3) bag2 contains...

  • Please help with this Java Program. Thank you! we will be implementing an Ordered List ADT....

    Please help with this Java Program. Thank you! we will be implementing an Ordered List ADT. Our goal is to implement the interface that is provided for this ADT. Notice that there are two interfaces: OrderedListADT builds on ListADT. In this homework, you'll only be responsible for the OrderedListADT. Figure 1: UML Overview 1 Requirements Create a doubly linked implementation of the OrderedListADT interface. Note that the book includes most of the source code for a singly linked implementation of...

  • Chapter 4 describes the ADT Sorted List using an array implementation with a maximum of 25...

    Chapter 4 describes the ADT Sorted List using an array implementation with a maximum of 25 items. The pseudocode for the ADT Sorted List Operations are provided on page 210. Use this information to create an ADT for handling a collection of Person objects, where each object will contain a Social Insurance Number (validate this), a first name, a last name, a gender and a data of birth. This implementation should prevent duplicate entries – that is, the Social Insurance...

  • Given a singly-linked list interface and linked list node class, implement the singly-linked list which has...

    Given a singly-linked list interface and linked list node class, implement the singly-linked list which has the following methods in Java: 1. Implement 3 add() methods. One will add to the front (must be O(1)), one will add to the back (must be O(1)), and one will add anywhere in the list according to given index (must be O(1) for index 0 and O(n) for all other indices). They are: void addAtIndex(int index, T data), void addToFront(T data), void addToBack(T...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT