-1

How do I make a get method for an ArrayList?

I have the method header but I have no idea how to proceed.

 public Object get(int i) {

      }
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
  • 2
    what language are you using? c# ? The question is not clear – Leandro Bardelli Oct 30 '14 at 16:56
  • java, sorry I forgot – HelloWorld Oct 30 '14 at 16:58
  • I literally just have no idea on how to proceed – HelloWorld Oct 30 '14 at 16:58
  • Is this homework? If so please state that it is. If it's not what is the purpose of this method. – Jonny Oct 30 '14 at 17:01
  • This is homework. Here are the instructions //Returns the element at index i in the arrayList. //UML is +get(i: int):Object – HelloWorld Oct 30 '14 at 17:02
  • Have you tried solving the problem? – Jonny Oct 30 '14 at 17:05
  • 1
    Welcome to StackOverflow. Questions like this aren't very well-received here. If you're having a specific problem, then we'll be happy to help you. We don't like it when you post homework questions and ask us to do them for you – Jason Baker Oct 30 '14 at 17:06
  • Yeah, but I've spent a solid hour thinking about it as well as the rest of the program. I figured that if I can solve this method I can solve the other methods, which include add() and size(). For some reason my professor seems to want us to actually write out the basic methods for an arrayList – HelloWorld Oct 30 '14 at 17:08

1 Answers1

1

What are you expecting to return from your get method? In java, ArrayList already has a get on it.. in C# also has a get defined on ArrayList but it is used differently.

I mean... if you are using an ArrayList this would be totally pointless and wrong... And i'm guessing your instructor wouldn't find it funny if you did:

public Object get(int i) {
     return myArrayList.get(i);
  }

or i mean you could beat around the bush and do this:

    public Object get(int i) {
Object[] myArray = new Object[myArrayList.size()];
myArray = myArrayList.toArray(myArray );
return myArray[i];
}
austin wernli
  • 1,801
  • 12
  • 15
  • I'm using java but for some reason we are required to write out another get method for our ArrayList. It'll have the exact same function as a normal get method – HelloWorld Oct 30 '14 at 17:00
  • It's common when learning to code to write you're own complementation of a existing method so that you gain an understanding of the mechanics of the language. In this case how a Java ArrayList works. – Jonny Oct 30 '14 at 17:06
  • Ah I see, I figured that since I still had to write a size() that I couldn't use it. Major slip up on my part, thank you so much. – HelloWorld Oct 30 '14 at 17:12