Homework 2 - /* 1. Add a constructor to the classes AList,...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
/* 1. Add a constructor to the classes AList, that creates a list from a given array of objects.*/ public AList(T[] givenArray) { length = givenArray.length; list = (T[]) new Object[length]; for (int index = 0; index < length; index++){ list[index+1] = givenArray[index]; } } // end constructor /*2. Suppose that you want an operation for the ADT list that returns the position of a given object in the list. The header of the method could be as follows: public int getPosition( T anObject) where T is the generic type of the objects in the list. Write an implemention of this method for each of the three classes described in this chapter.*/ public int getPosition(T anObject) { int result = null; // result to return int lastIndex = length - 1; for(int index=0; index < lastIndex; index++){ if(anObject.equals(list[index])){ result = index; } } return result; } // end getPosition /*3. Suppose that you want an operation for the ADT list that removes the first occurrence of a given object from the list. The header of the method could be as follows: public boolean remove( T anObject) where T is the generic type of the objects in the list. The method returns true if the list contained anObject and that object was removed. Write an implementation of this method for each of the three classes described in this chapter. */ public boolean remove(T anObject) { boolean result = false; // result to return int lastIndex = length - 1; for(int index=0; index < lastIndex; index++){ if(anObject.equals(list[index])){
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
removeGap(index+1); length--; result =true; } } return result; } // end remove /*4. Suppose that you want an operation for the ADT list that moves the first item in the list to the end of the list. The header of the method could be as follows: public void moveToEnd() Write an implemention of this method for each of the three classes described in this chapter.*/ private void moveToEnd() { // assert (newPosition >= 1) & (newPosition <= length + 1); int lastIndex = length - 1; T firstObject = list[0]; T lastObject = list[lastIndex]; list[0]= lastObject; list[lastIndex]= firstObject; } // end moveToEnd /*5. Exercise 7 in the previous chapter asked you to write statements at the client level that replace an object in a given list. Write a method at the client level that performs such a
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 8

Homework 2 - /* 1. Add a constructor to the classes AList,...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online