Question

I’m giving you code for a Class called GenericArray, which is an array that takes a...

I’m giving you code for a Class called GenericArray, which is an array that takes a generic object type.

As usual this is a C# program, make a new console application, and for now you can stick all of this in one big file.

And a program that will do some basic stuff with it

Generic Array List What I want you to do today:

Create methods for the GenericArray,

Easy(ish):

public void Append (T, value) {

// this should add T to the array at the next available index.

// to do this you should probably change the class to keep track of the ‘current’ index, and then only ‘append’ items to the array at the current index. Easy Enough.

}

public void PrintAll(){

//for every element in the array, just print the [index] and the value

// assume that the object has some way to be displayed (so you don’t have to do anything to make this work if the generic type are integers, floats or strings etc.

// so something like System.Console.WriteLine(getItem(i)); should work to print the value.

}

Moderate:

        public bool Find(T value)

        {

            // given some value, search the array and see if it exists, if it does return true, if not return false.

           

        }

Change the ‘Grow’ method to your own implementation, where you create a new array (double the size of the previous one) and copy all of the previous elements over

Private void Insert (T value)

{

               //Insert should *insert* a value at an index by shifting all elements down by one

               // Make sure to check if the array is big enough first, and if not, grow it

}

Advanced:

Change printAll to return a string, and then have the main program print that String

public string printAll(){

// now, rather than the list itself being responsible for printing, it should return a string (formatted somehow) that should be printable

}

this is the code i will provide you

public class GenericArray<T>
{
private T[] array;

public GenericArray(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
if (index >= array.Length)
Grow(array.Length * 2);

array[index] = value;
}
public void Grow(int newsize)
{
Array.Resize(ref array, newsize);
}
}
}
class Program
{
static void Main(string[] args)
{
GenericArray<int> array2;
int numelements = 5;
array2 = new GenericArray<int>(numelements);

for (int i = 0; i < numelements; i++)
{
array2.setItem(i, i * 2);
}
for (int i = 0; i <= numelements; i++)
{
Console.WriteLine(array2.getItem(i));
}
Console.ReadLine();
}
}
}

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

using System;

namespace Rextester

{

    // program would work best if you start with size 1

    public class GenericArray<T>

    {

        private T[] array;

        public GenericArray(int size)

        {

            array = new T[size];

        }

        

        public T getItem(int index)

        {

            return array[index];

        }

       

        public void setItem(int index, T _value)

        {

            if (index >= array.Length)

            {

                Grow(array.Length + 1);

            }

            array[index] = _value;

        }

       

        public void Grow(int newsize)

        {

            Array.Resize(ref array, newsize);

        }   

       

        public void Append (T _value)

        {

            // this should add T to the array at the next available index.

            // to do this you should probably change the class to keep track of the ‘current’ index, and then only ‘append’ items to the array at the current index. Easy Enough.

           

          // set the new value at the end of the array

            setItem( array.Length , _value );

        }

       

        public bool Find(T _value)

        {

            // given some value, search the array and see if it exists, if it does return true, if not return false.

           

            int i;

           

            for( i = 0 ; i < array.Length ; i++ )

                // if element is found

                if( array[i].Equals(_value) )

                    return true;

               

            return false;

        }

       

        private void Insert (int index, T _value)

        {

           //Insert should *insert* a value at an index by shifting all elements down by one

           // Make sure to check if the array is big enough first, and if not, grow it

           

           // if the index is greater than the size of array

           if( index >= array.Length )

               // increase the size of array

               Grow(array.Length + 1);

          

            int i;

           

            // shift all elements one position right after element at index

            for( i = array.Length - 1 ; i >= index ; i++ )

                array[i + 1] = array[i];

           

            array[index] = _value;

        }

        public void PrintAll()

        {

            //for every element in the array, just print the [index] and the value

            // assume that the object has some way to be displayed (so you don’t have to do anything to make this work if the generic type are integers, floats or strings etc.

            // so something like System.Console.WriteLine(getItem(i)); should work to print the value.

            int i;

           

            for( i = 0 ; i < array.Length ; i++ )

                Console.WriteLine("[" + i + "] : " + array[i]);

        }

       

        public string printAll2()

        {

            // now, rather than the list itself being responsible for printing, it should return a string (formatted somehow) that should be printable

           

            int i;

           

            String ans = "";

           

            for( i = 0 ; i < array.Length ; i++ )

                ans += "[" + i.ToString() + " ] : " + array[i].ToString() + "\n";

           

            return ans;

        }

    }

   

    public class Program

    {

        public static void Main(string[] args)

        {

            //Your code goes here

            Console.WriteLine("Hello, world!");

            GenericArray<int> array2;

       

            int numelements = 1;

            array2 = new GenericArray<int>(numelements);

            for (int i = 0; i <= 5; i++)

            {

                array2.setItem(i, i * 2);

            }

            //for (int i = 0; i <= 5; i++)

            //{

            //    Console.WriteLine(array2.getItem(i));

            //}

           

            Console.WriteLine(array2.printAll2());

           

            Console.WriteLine("Is 4 present in array : " + array2.Find(4));

            Console.WriteLine("Is 5 present in array : " + array2.Find(5));

           

            array2.Append(20);

           

            array2.PrintAll();

        }

    }

}

Sample Output

Hello, world!
[0 ] : 0
[1 ] : 2
[2 ] : 4
[3 ] : 6
[4 ] : 8
[5 ] : 10

Is 4 present in array : True
Is 5 present in array : False
[0] : 0
[1] : 2
[2] : 4
[3] : 6
[4] : 8
[5] : 10
[6] : 20
Add a comment
Know the answer?
Add Answer to:
I’m giving you code for a Class called GenericArray, which is an array that takes a...
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
  • 23.1 Append to Oversize Array Java Help Given an oversize array with size1 elements and a...

    23.1 Append to Oversize Array Java Help Given an oversize array with size1 elements and a second oversize array with size2 elements, write a method that returns the first array with the elements of the second appended to the end. If the capacity of the oversize array is not large enough to append all of the elements, append as many as will fit. Hint: Do not construct a new array. Instead, modify the contents of the oversize array inside the...

  • IN C# The fun for today is to build your own circular array to support a...

    IN C# The fun for today is to build your own circular array to support a queue. The challenge here is in adjusting your queueFront and queueRear markers (they are just integer array indices), and dealing with what happens when they wrap around the First/last element of the array. The tricky part here is worrying about the edge cases. There are only two methods you need to fix up addBack – this should correctly add an item at the rear...

  • Modify the LinkedCollection class to be a SortedLinkedCollecton class and see how that effects our implementation...

    Modify the LinkedCollection class to be a SortedLinkedCollecton class and see how that effects our implementation for adding and removing items. You should reference the SortedArrayCollection class provided for how these algorithms should be implemented. What needs to change here? Is it a lot of code or not much? Include a toString method that creates and returns a string that correctly represents the current collection. Include a test driver application that demonstrates your class correctly. //--------------------------------------------------------------------------- // LinkedCollection.java // //...

  • Design a program that allows you to experiment with different sort algorithms in Java. This program should allow you to...

    Design a program that allows you to experiment with different sort algorithms in Java. This program should allow you to easily plug-in new sort algorithms and compare them. Assume that input data is generated randomly and stored in a text file (have no less than 2000 items to sort). Do not restrict your program to only one data type, or to one ordering relationship. The data type, ordering relationship, and the sorting method must be input parameters for your program....

  • JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

    JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity    private T[] data;   //underlying array    // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!       @SuppressWarnings("unchecked")    public SmartArray(){        //constructor        //initial capacity of the array should be DEFAULT_CAPACITY    }    @SuppressWarnings("unchecked")    public SmartArray(int initialCapacity){        // constructor        // set the initial capacity of...

  • Can someone please explain this piece of java code line by line as to what they...

    Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments). Code: import java.util.*; public class Array { private Integer[] array; // NOTE: Integer is an Object. Array() {     super();     array = new Integer[0]; } Array(Array other) {     super();     array = other.array.clone(); // NOTE: All arrays can be cloned. } void add(int value) {    ...

  • please illistrate a UML diagram for the following code bellow, it should have 3 rows, 1...

    please illistrate a UML diagram for the following code bellow, it should have 3 rows, 1 colum like the one bellow, first box should have the class name, second box is for class attributes, and third box should have the class operations/methods and please put a (+) for public and a (-) for private example: class +-attributes +-Operations Also make a JAVADOCs, but not generated by a compiler, to explain what is going on in the code import java.util.Random; public...

  • you will write a templated array class. Called MyArray with member variables ptr and array_size. This...

    you will write a templated array class. Called MyArray with member variables ptr and array_size. This array must use dynamic memory--see program shell, names should remain unchanged. The following is a list of required member functions of the array class along with a rubric: (1pts) program compiles (2pts) default constructor (2pts) parametered constructor which feeds MyArray a size. (10pts) copy constructor 8pts for performing a *deep* copy 2pts for correct syntax (10pts) overloaded = operator 7pts for functioning properly 3pts...

  • JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

  • write a program which include a class containing an array of words (strings).The program will search...

    write a program which include a class containing an array of words (strings).The program will search the array for a specific word. if it finds the word:it will return a true value.if the array does not contain the word. it will return a false value. enhancements: make the array off words dynamic, so that the use is prompter to enter the list of words. make the word searcher for dynamic, so that a different word can be searched for each...

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
ADVERTISEMENT